【问题标题】:use python script in node.js在 node.js 中使用 python 脚本
【发布时间】:2021-01-11 15:47:37
【问题描述】:

如何从我的 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 “子进程”中使用

【问题讨论】:

  • 在另一篇文章中提到了从 Node js 调用脚本的一般方法:stackoverflow.com/questions/44647778/… 通常,与任何其他类型的脚本相比,它与 Python 脚本的关系并不多。然而,下面的 kabirbaidhya 有很好的 Python 细节。

标签: javascript python node.js


【解决方案1】:

最简单的方法是使用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")

你的节点脚本应该输出:

Result: Hello World

一旦你得到它的工作,你可以用你的python脚本替换它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多