Sometimes, we want to call Python function from JavaScript code.
In this article, we’ll look at how to call Python function from JavaScript code.
How to call Python function from JavaScript code?
To call Python function from JavaScript code, we run the Python script from the Node.js script with spawn
.
For instance, we write
const { spawn } = require("child_process");
const temperatures = [];
const sensor = spawn("python", ["sensor.py"]);
sensor.stdout.on("data", (data) => {
temperatures.push(parseFloat(data));
console.log(temperatures);
});
to call spawn
with 'python'
and an array with the arguments which includes the path to the script file to run.
Then we listen for stdout changes with
sensor.stdout.on("data", (data) => {
temperatures.push(parseFloat(data));
console.log(temperatures);
});
to get the output from data
and so things with it in the callback.
Conclusion
To call Python function from JavaScript code, we run the Python script from the Node.js script with spawn
.