Shivam Saini
Shivam Saini

Reputation: 23

use python script in node.js

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"

Upvotes: 2

Views: 124

Answers (1)

kabirbaidhya
kabirbaidhya

Reputation: 3490

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.

Upvotes: 4

Related Questions