【问题标题】:How should I use child_process module to communicate python and node.js in linux?我应该如何使用 child_process 模块在 linux 中通信 python 和 node.js?
【发布时间】:2018-04-04 17:24:45
【问题描述】:

我正在尝试从 node.js 调用 python 文件。 这是流程/结构:当 node.js 接收到某个值(通过套接字从前端)--运行 python 文件(不一定接收特定输入)--python 文件将在同一目录中创建并保存 .png 文件。

我在 npm 模块中尝试了 python-shell,但它不断给出错误,似乎它希望我将所有导入的包移动/复制到该 .js 文件所在的位置......

所以我正在寻找一个替代方案,并找到了 child_process 模块。 下面的问题是我不确定要在下面的代码中放入 var pythonExecutable 什么,因为我的计算机是 linux,而不是 windows。

如果对上述所有方法发表任何评论,我将不胜感激。

我指的是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);
});

【问题讨论】:

    标签: javascript python node.js child-process


    【解决方案1】:
    var pythonExecutable = "python"; 
    

    会的。如果您使用 python.exe 您告诉进程运行 windows .exe 命令。只是“python”会这样做,如果没有安装python,它会抛出一个错误“python command not found”或类似的错误

    【讨论】:

    • 谢谢!我假设如果我在 python3 中运行,我可以输入“python3”代替?
    • 是的,你可以。但是,如果您只想使用 python 命令运行 python3,您也可以在终端中执行 alias python=python3,如果您的所有问题都已回答,则可以将其标记为解决问题。
    猜你喜欢
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2015-01-06
    • 1970-01-01
    • 2017-05-18
    相关资源
    最近更新 更多