我应该如何使用child_process模块与linux中的python和node.js通信?
How should I use child_process module to communicate python and node.js in linux?
我正在尝试从 node.js 调用 python 文件。
这是 flow/structure:当 node.js 接收到特定值(通过套接字从前端)时 -- 运行 python 文件(不一定接收特定输入)-- python 文件将在同一目录中创建并保存 .png 文件。
我在 npm 模块中尝试了 python-shell,但它一直出现错误,似乎它想让我 move/copy 所有导入的包到那个 .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);
});
var pythonExecutable = "python";
会的。如果你使用 python.exe
你告诉进程 运行 windows .exe 命令。只需 "python" 即可 如果 python 未安装
则会抛出错误 "python command not found" 或类似错误
我正在尝试从 node.js 调用 python 文件。 这是 flow/structure:当 node.js 接收到特定值(通过套接字从前端)时 -- 运行 python 文件(不一定接收特定输入)-- python 文件将在同一目录中创建并保存 .png 文件。
我在 npm 模块中尝试了 python-shell,但它一直出现错误,似乎它想让我 move/copy 所有导入的包到那个 .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);
});
var pythonExecutable = "python";
会的。如果你使用 python.exe
你告诉进程 运行 windows .exe 命令。只需 "python" 即可 如果 python 未安装