Communicating Between Nodejs And Python: Passing Back Multiple Arguments
Solution 1:
There isn't an interface that communicate directly between Node.js and Python, so you can't pass custom arguments, what you're doing is just executing a python program using child_process
, so you don't send arguments, anything that is received on 'data'
its what is printed to stdout
from python.
So what you need to do, is serialize the data, and then deserialize it in Node, you can use JSON
for this.
From your python script, output the following JSON
object:
{"thing1":"Hot","thing2":"Cold","thing3":"Warm"}
And in your Node.js script:
const spawn = require('child_process').spawn;
const pythonProcess = spawn('python', ["/path/to/python/file"]);
const chunks = [];
pythonProcess.stdout.on('data', chunk => chunks.push(chunk));
pythonProcess.stdout.on('end', () => {
try {
// If JSON handle the dataconst data = JSON.parse(Buffer.concat(chunks).toString());
console.log(data);
// {// "thing1": "Hot",// "thing2": "Cold",// "thing3": "Warm"// }
} catch (e) {
// Handle the errorconsole.log(result);
}
});
Have in mind that data
is chunked, so will have to wait until the end
event is emitted before parsing the JSON
, otherwise a SyntaxError
will be triggered. (Sending JSON from Python to Node via child_process gets truncated if too long, how to fix?)
You can use any type of serialization you feel comfortable with, JSON
is the easiest since we're in javascript.
Note that stdout
is a stream, so it's asyncrhonous, that's why your example would never work.
pythonProcess.stdout.on('data', (data) => {
thing1 = data[0];
thing2 = data[1];
thing3 = data[2];
})
// Things do not exist here yetconsole.log('thing1: ' + thing1);
console.log('thing2: ' + thing2);
console.log('thing3: ' + thing3);
Post a Comment for "Communicating Between Nodejs And Python: Passing Back Multiple Arguments"