For projects involving machine learning algorithms implemented in Python, integrating these functions into Node.js applications can be a seamless process. Here's how to achieve this using the "child_process" package in Node.js.
const { spawn } = require("child_process");
const pythonProcess = spawn('python', ["path/to/script.py", arg1, arg2, ...]);
In the Python script, ensure that you import the "sys" module. Access arguments from Node.js using:
# In Python script import sys arg1 = sys.argv[1] arg2 = sys.argv[2]
To return data to Node.js, use:
# In Python script print(dataToSendBack) sys.stdout.flush()
In Node.js, listen for data using:
pythonProcess.stdout.on('data', (data) => { // Handle received data });
By passing multiple arguments to the Python script, you can design the script to handle different functions based on a specified argument. This allows you to reuse the script for various function calls.
The above is the detailed content of How to Invoke Python Functions from Your Node.js Applications?. For more information, please follow other related articles on the PHP Chinese website!