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