Search code examples
javascriptpythonnode.jsno-response

No Response After Running Python Script Using Python-Shell


I have a nodeJS application and I need to run a python script in order to get a certain response. I am using python-shell in order to do that, but I am getting no response.

I have tried also using a child-process, same response.

Here I call the python script:

var ps = require('python-shell');
ps.PythonShell.run('./face_detect.py', array1, function (err, data) {
    if (err) req.send(err);
    req.send(data.toString())
}); 

This is a snippet of my python script:

import cv2
import sys
import os
import numpy as np

students = sys.argv[1]
# get the names and put them in an array ---> subjects
imagePath = "class/welcome.jpg"
cascPath = "haarcascade_frontalface_alt.xml"

faceCascade = cv2.CascadeClassifier(cascPath)

.....
for (x, y, w, h) in faces:
    num = 0
    crop_img = cv2.UMat(image[y-40:y+h+100,x-40:x+h+40])
    cv2.imwrite("face" + str(num) + ".jpg", crop_img)
    test_img = cv2.imread("face" + str(num) + ".jpg")
    num = num + 1
    predicted_img1 = predict(test_img)
absences["A"] = 1
for name, a in absences.items():
    if a == 0:
        noshow.append(name)
print(noshow)
cv2.waitKey(0)

I expect it to return an array. Can anyone help me with this?


Solution

  • The correct syntax for passing argument from Nodejs python-shell to Python script is:

    ps.PythonShell.run('./face_detect.py', { args: array1 }, function (err, data) { ... })
    

    Here the value of sys.argv[1] in your Python script will not contain the Nodejs array1 value because you don't set the args property in your PythonShell options.

    Note also this should probably be res.send instead of req.send, depending on your program, and I advise you to return if there is an error to prevent "headers already sent" exception.