【发布时间】:2018-04-04 17:24:45
【问题描述】:
我正在尝试从 node.js 调用 python 文件。 这是流程/结构:当 node.js 接收到某个值(通过套接字从前端)--运行 python 文件(不一定接收特定输入)--python 文件将在同一目录中创建并保存 .png 文件。
我在 npm 模块中尝试了 python-shell,但它不断给出错误,似乎它希望我将所有导入的包移动/复制到该 .js 文件所在的位置......
所以我正在寻找一个替代方案,并找到了 child_process 模块。 下面的问题是我不确定要在下面的代码中放入 var pythonExecutable 什么,因为我的计算机是 linux,而不是 windows。
如果对上述所有方法发表任何评论,我将不胜感激。
// The path to your python script
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);
});
【问题讨论】:
标签: javascript python node.js child-process