Home > Backend Development > Python Tutorial > How can I call Python functions and receive data back in my Node.js application?

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

Linda Hamilton
Release: 2024-11-14 15:04:02
Original
436 people have browsed it

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, ...]);
Copy after login

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]
Copy after login

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

print(dataToSendBack)
sys.stdout.flush()
Copy after login

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
});
Copy after login

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.

The above is the detailed content of How can I call Python functions and receive data back in my Node.js application?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template