簡體   English   中英

在 node.js 中使用 python 腳本

[英]use python script in 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")

您的節點腳本應輸出:

Result: Hello World

一旦你讓它工作,你可以用你的python腳本替換它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM