javascript - 在node.js中使用python脚本

标签 javascript python node.js

如何从我的 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/

相关文章:

python - 用python解析json

Node.js 应用程序未在 AWS Elastic Beanstalk 上运行

javascript - 在不正确的路线上收到错误消息

c# - 如何从第二个重定向页面更新第一个页面?

python - 为什么我的代码没有返回斜边的值?

python - 组和 channel 层使流程停止而不会引发异常

javascript - Safari 扩展 : WebSocket connection failure calls onclose and not onerror and no exception

javascript - 分配给数组无法按预期工作

Node.js 套接字同时发送和接收

javascript:从另一个 json 对象中获取默认值 - 以不同的排序顺序处理数组