首頁  >  文章  >  後端開發  >  如何在 Node.js 應用程式中呼叫 Python 函數並接收傳回的資料?

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

Linda Hamilton
Linda Hamilton原創
2024-11-14 15:04:02372瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn