使用node.js child_process调用python脚本

我试图从我的节点文件调用一个Python代码。

这里是我的node.js代码:

var util = require("util"); var spawn = require("child_process").spawn; var process = spawn('python',["workpad.py"]); util.log('readingin') process.stdout.on('data',function(data){ util.log(data); }); 

和我的Python部分:

 import sys data = "test" print(data) sys.stdout.flush() 

在cmd窗口中,只显示util.log('readingin') 。 我的代码有什么问题?

没有问题 …

这里是你的工作代码的轻微调整(我把缓冲区转换为string,使其人类可读)

 // spawn_python.js var 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); }); 

这里是你的python

 # python_launched_from_nodejs.py import sys data = "this began life in python" print(data) sys.stdout.flush() 

最后这里是一个运行的输出

 node spawn_python.js 11 Dec 00:06:17 - readingin 11 Dec 00:06:17 - this began life in python 

节点 – 版本

V5.2.0

你的python代码是不正确的:

 import sys data = "test" print(data) ###not test sys.stdout.flush() 

我也面临同样的问题,我发现这一点 :

 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 string var uint8arrayToString = function(data){ return String.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); }); 

你总是可以尝试这样的事情:

 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); } });