Call Python Script Using Node.js Child_process
I was trying to call a python code from my node file. Here is my node.js Code: var util = require('util'); var spawn = require('child_process').spawn; var process = spawn('python
Solution 1:
There is no problem ...
Here is a slight tweak of your working code (I convert the buffer to string so its human readable)
// spawn_python.jsvar util = require("util");
var spawn = require("child_process").spawn;
var process = spawn('python',["python_launched_from_nodejs.py"]);
util.log('readingin')
process.stdout.on('data',function(chunk){
var textChunk = chunk.toString('utf8');// buffer to string
util.log(textChunk);
});
and here is your python
# python_launched_from_nodejs.py
import sys
data = "this began life in python"
print(data)
sys.stdout.flush()
finally here is output of a run
node spawn_python.js
11 Dec 00:06:17 - readingin
11 Dec 00:06:17 - this began life in python
node --version
v5.2.0
Solution 2:
I was also facing the same issue, I found this:
var myPythonScript = "script.py";
// Provide the path of the python executable, if python is available as // environment variable then you can use only "python"var pythonExecutable = "python.exe";
// Function to convert an Uint8Array to a stringvar uint8arrayToString = function(data){
returnString.fromCharCode.apply(null, data);
};
const spawn = require('child_process').spawn;
const scriptExecution = spawn(pythonExecutable, [myPythonScript]);
// Handle normal output
scriptExecution.stdout.on('data', (data) => {
console.log(uint8arrayToString(data));
});
// Handle error output
scriptExecution.stderr.on('data', (data) => {
// As said before, convert the Uint8Array to a readable string.console.log(uint8arrayToString(data));
});
scriptExecution.on('exit', (code) => {
console.log("Process quit with code : " + code);
});
Solution 3:
Your python code is not correct:
import sys
data = "test"
print(data) ###not test
sys.stdout.flush()
Solution 4:
You could always try something like this:
var child_process = require('child_process');
child_process.exec('python myPythonScript.py', function (err){
if (err) {
console.log("child processes failed with error code: " + err.code);
}
});
Post a Comment for "Call Python Script Using Node.js Child_process"