我正在尝试使用NodeJS来执行多个python脚本,并将这些脚本的内容发送到本地主机。我不想具体到确切的python脚本,而是使用类似于使用".py“执行python脚本的东西。
我尝试运行多个进程,但最后一个进程在本地主机上覆盖了前一个进程。
Python脚本:
hellothere.py
print("hello there")
helloworld.py
print("Hello World!")
Goodbye.py
print("Goodbye!")
Pythonspawn.js
var express = require('express');
var app = express();
app.get('/name', function callName(req, res) {
var spawn = require("child_process").spawn;
var PythonProcess1 = spawn('python',["./hellothere.py"] );
var PythonProcess2 = spawn('python', ['./helloworld.py']);
var PythonProcess3 = spawn('python', ['./Goodbye.py']);
PythonProcess1.stdout.on('data', function(data) {
res.send(data.toString());
})
PythonProcess2.stdout.on('data', function(data) {
res.send(data.toString());
})
PythonProcess3.stdout.on('data', function(data) {
res.send(data.toString());
})
}
})
app.listen(1820, function() {
console.log('Server is running on port %d.', this.address().port);
})
我想执行任何使用".py“的python脚本,而不是指定我想要执行的确切脚本。如果可能,我也想执行脚本,如果它们有不同数量的参数。(即,如果helloworld.py有两个sys.argi,而Goodbye.py有一个sys.argi。)
发布于 2019-06-11 03:14:10
你可以在这里使用exec(),我在这里检查当前工作目录中的所有.js文件,执行它,并将结果添加到一个数组中,最后返回它。
const { exec } = require('child_process');
var result = [];
exec('ls | grep .js', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
var s = stdout.split('\n');
s.pop();
console.log(s);
executeFiles(s);
});
function executeFiles(filenames) {
filenames.forEach((element, index) => {
exec(`node ${element}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(stdout);
result.push(stdout.toString());
if (index === filenames.length - 1) {
console.log(result);
return result;
}
});
});
}
https://stackoverflow.com/questions/56531914
复制相似问题