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.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!