首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我可以使用child_process在一台服务器上生成多个python输出吗?

我可以使用child_process在一台服务器上生成多个python输出吗?
EN

Stack Overflow用户
提问于 2019-06-11 02:45:41
回答 1查看 303关注 0票数 0

我正在尝试使用NodeJS来执行多个python脚本,并将这些脚本的内容发送到本地主机。我不想具体到确切的python脚本,而是使用类似于使用".py“执行python脚本的东西。

我尝试运行多个进程,但最后一个进程在本地主机上覆盖了前一个进程。

Python脚本:

hellothere.py

代码语言:javascript
复制
 print("hello there")

helloworld.py

代码语言:javascript
复制
 print("Hello World!")

Goodbye.py

代码语言:javascript
复制
 print("Goodbye!")

Pythonspawn.js

代码语言:javascript
复制
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。)

EN

回答 1

Stack Overflow用户

发布于 2019-06-11 03:14:10

你可以在这里使用exec(),我在这里检查当前工作目录中的所有.js文件,执行它,并将结果添加到一个数组中,最后返回它。

代码语言:javascript
复制
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;
      }
    });
  });
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56531914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档