我应该如何使用child_process模块来与python和节点.js在linux中?

2024-09-22 16:36:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从节点.js. 这是流程/结构:什么时候节点.js从python接收特定的png文件(不一定要从python.end文件接收)中创建特定的输入(不需要保存在python.end文件中)。在

我试过在npm模块中使用pythonshell,但它总是给出错误,似乎它希望我将所有导入的包移动/复制到.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);
});

Tags: 文件thetologoutputdataonvar
1条回答
网友
1楼 · 发布于 2024-09-22 16:36:22
var pythonExecutable = "python"; 

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

相关问题 更多 >