简体   繁体   English

我应该如何使用child_process模块​​在linux中通信python和node.js?

[英]How should I use child_process module to communicate python and node.js in linux?

I'm trying to call python file from node.js. 我正在尝试从node.js调用python文件。 This is the flow/structure: when node.js receives certain value (from frontend via socket) -- run python file (not neccesarily receiving specific input) -- python file will create and save .png file in the same directory. 这是流程/结构:当node.js收到某个值(通过套接字从前端)时-运行python文件(不必接收特定的输入)-python文件将在同一目录中创建并保存.png文件。

I tried python-shell in npm modules, but it's keep giving the errors and seems like it wants me to move/copy all imported packages to where that .js file is... 我在npm模块中尝试了python-shell,但是它一直在给出错误,并且似乎要我将所有导入的包移动/复制到.js文件所在的位置...

So I'm looking an alternative, and found child_process module. 所以我在寻找一个替代方案,并找到了child_process模块。 The problem below is that I'm not sure what to put in var pythonExecutable in the code below, since my computer is linux, not windows. 下面的问题是我不确定在下面的代码中放入var pythonExecutable ,因为我的计算机是Linux,而不是Windows。

I would appreciate any comment about the methods all above. 对于上述所有方法,我将不胜感激。

I'm referring to this code from https://ourcodeworld.com/articles/read/286/how-to-execute-a-python-script-and-retrieve-output-data-and-errors-in-node-js 我是从https://ourcodeworld.com/articles/read/286/how-to-execute-a-python-script-and-retrieve-output-data-and-errors-in-node- js

// 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"; 

will do. 会做。 if you use python.exe your telling the process to run the windows .exe command. 如果使用python.exe告诉进程运行Windows .exe命令。 just "python" will do it will throw an error "python command not found" or similar if python is not install 如果没有安装python,则仅执行“ python”将抛出错误“找不到python命令”或类似的错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM