Skip to content

How to call python script from NodeJs

I need to call this python script in NodeJs.

#!/usr/bin/env python
# -*- coding: utf8 -*-

import RPi.GPIO as GPIO
import MFRC522
import signal

continue_reading = True

# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
    global continue_reading
    print "Ctrl+C captured, ending read."
    continue_reading = False

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# Welcome message
print "Welcome to the MFRC522 data read example"
print "Press Ctrl-C to stop."

# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:

    # Scan for cards    
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

    # If a card is found
    if status == MIFAREReader.MI_OK:
    # Get the UID of the card
    (status,uid) = MIFAREReader.MFRC522_Anticoll()

    # If we have the UID, continue
    if status == MIFAREReader.MI_OK:

        # Print UID
        print "Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3])

        # This is the default key for authentication
        key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]

        # Select the scanned tag

        # Authenticate
        status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)

        # Check if authenticated
        if status == MIFAREReader.MI_OK:
            print "Authentication error"

I used python-shell, here is the NodeJs code for that


var PythonShell = require('python-shell');

var options = {
scriptPath: '/home/pi/gpio-admin/MFRC522-python/'
var pyshell = new PythonShell('',options);

pyshell.on('message', function (message) {


But when I ran this code I didn’t see anything in Node side. I think problem occurs when python script comes to this level.

   (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

Because I just ran with while loop which has only print statement then it works. After that I tried another way to achieve this. But I got same problem which I have with above.Here is another method


var python = require('child_process').spawn(
 // second argument is array of parameters, e.g.:
 var output = "";
 python.stdout.on('data', function(){ 

    output += data ;
 python.on('close', function(code){ 

   console.log("Here you are there...");

Any help would be appreciated



There are multiple ways of doing this.

  • first way is by doing npm install python-shell

and here’s the code

var PythonShell = require('python-shell');
//you can use error handling to see if there are any errors'', options, function (err, results) { 
//your code

you can send a message to python shell using pyshell.send('hello');

you can find the API reference here-

a few more references –

if you want to use service-oriented architecture –