如何从我的 Node.js 应用程序调用 Python 函数以利用 python 的face_recognition 库,我是 python 环境的新手。 这是我的 python 脚本
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')
如何修改它以能够在node.js“子进程”中使用
最佳答案
最简单的方法是使用 child_process.exec
执行 python 脚本并捕获结果。
这是您需要的代码:
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);
});
根据您的本地设置更新以下变量并运行它:
PYTHON_PATH
指向您的 python 可执行文件路径SCRIPT_PATH
到 Python 脚本的绝对(或相对)路径。
这只会调用脚本并从标准输出捕获其输出。
假设,如果您的 python 脚本 script.py
定义如下:
print("Hello World")
您的 Node 脚本应输出:
Result: Hello World
一旦你让它工作起来,你就可以用你的Python脚本替换它。
关于javascript - 在node.js中使用python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64061892/