在Node JS中生成python中的子进程

时间:2017-03-16 14:04:01

标签: javascript python node.js ubuntu

我在app.js for Windows中编写了以下代码

app.js

app.route('/file').post(function (req,res,next) {
// 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 path =resolve("C:\\Python27\\python.exe");
var pythonExecutable = path;
var macadd =req.body.macadd;
var percent =req.body.percent;
// 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(String.fromCharCode.apply(null, data));
});
var data = JSON.stringify([1,2,3,4,5]);
scriptExecution.stdin.write(data);
// End data write
scriptExecution.stdin.end();
});

如您所见,提供了python可执行文件的路径。此代码在Windows中正常工作,并在控制台上提供数组中的数字总和。我想在Ubuntu中执行相同的代码。我在Linux(Ubuntu)中为python可执行文件路径指定了什么?

2 个答案:

答案 0 :(得分:1)

这将取决于Linux设置中python可执行文件的位置。

正如你所说它是一个Ubuntu(没有指定版本),你可以尝试使用没有路径的python,因为python可执行文件应该已经在PATH中了,通常它随你的安装分配。

如果这不起作用,你可以找出在Linux shell上运行which python的python可执行文件路径。

最后,您还可以尝试使用/usr/bin/python作为可执行路径,因为它是通常的位置。

答案 1 :(得分:0)

您可以使用process.platform获取当前平台。 例如,在我的Mac上,我有process.platform === 'darwin'documentation

相关问题