2

how to call Python functions from my Node.js application to make use of face_recognition library of python, i am new to python environment. this is my python script

import face_recognition

A = face_recognition.load_image_file('C:/Users/shivam/Desktop/facenet/database/x.jpg')
A_face_encoding = face_recognition.face_encodings(A)[0]

B = face_recognition.load_image_file('C:/Users/shivam/Desktop/facenet/database/y.jpg')
B_face_encoding = face_recognition.face_encodings(B)[0]

 # Compare faces
results = face_recognition.compare_faces([A_face_encoding], B_face_encoding)

if results[0]:
    print('Verified')
else:
    print('Unverified')

how to modify it to be a able to use in node.js "child process"

kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59
  • 1
    A general way to call scripts from Node js is mentioned here in another article: https://stackoverflow.com/questions/44647778/how-to-run-shell-script-file-using-nodejs Typically, it's not more involved with a Python script than any other kind of script. kabirbaidhya below however, has good detail on Python. – Harlin Sep 25 '20 at 13:10

1 Answers1

4

Simplest way is to use child_process.exec to execute your python script and capture the result.

Here's the code you need:

const child_process = require('child_process');

const PYTHON_PATH = '/usr/bin/python3'; // Set the path to python executable.
const SCRIPT_PATH = 'script.py'; // Path to your python script

const command = `${PYTHON_PATH} "${SCRIPT_PATH}"`;

child_process.exec(command, function (error, stdout, stderr) {
  if (error) {
    console.error(`ERROR: ${error.message}`);
    return;
  }

  if (stderr) {
    console.error(`ERROR: ${stderr}`);
    return;
  }

  // Do something with the result in stdout here.
  console.log('Result:', stdout);
});

Update the following vars as per your local setup and run it:

  • PYTHON_PATH to point to your python executable path and
  • SCRIPT_PATH to the absolute (or relative) path of your python script.

This would just call the script and capture it's output from stdout.

Suppose, if you have the python script script.py defined like this:

print("Hello World")

Your node script should output:

Result: Hello World

Once you get it working, you can replace it with your python script.

Dharman
  • 30,962
  • 25
  • 85
  • 135
kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59