如何在 Node.js 應用程式中呼叫 Python 函數並接收傳回的資料?

Linda Hamilton
發布: 2024-11-14 15:04:02
原創
371 人瀏覽過

How can I call Python functions and receive data back in my Node.js application?

Calling Python Functions from Node.js

Incorporating machine learning capabilities into Node.js applications can be achieved by leveraging Python's robust ML libraries. Here's how to establish seamless communication between Node.js and Python:

The "child_process" module included in Node.js provides a convenient way to execute Python scripts. By utilizing the 'spawn' method, you can launch a Python process with specified arguments:

const spawn = require('child_process').spawn;
const pythonProcess = spawn('python', ['path/to/script.py', arg1, arg2, ...]);
登入後複製

In the Python script, ensure you import the 'sys' module. Arguments passed from Node.js can be accessed through 'sys.argv':

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]
登入後複製

To relay data from Python back to Node.js, simply print it and flush the standard output:

print(dataToSendBack)
sys.stdout.flush()
登入後複製

In Node.js, subscribe to the 'data' event on the Python process's standard output:

pythonProcess.stdout.on('data', (data) => {
  // Handle data returned from the Python script
});
登入後複製

Since 'spawn' allows multiple arguments, you can design your Python script to handle a range of functions and arguments. This flexibility enables you to call specific Python functions with their respective arguments from within Node.js.

以上是如何在 Node.js 應用程式中呼叫 Python 函數並接收傳回的資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板