NodeJS和Python-Shell .run函数不打印STDOUT

时间:2018-01-12 10:40:29

标签: javascript python node.js shell

我使用的是NodeJS和Python脚本。

我需要从我的python脚本中获取结果,为此,我使用Python-Shell。 请参阅此链接中的文档:

Person

我可以使用pythonShell.on和pythonShell.end来获取打印件。

问题在于我无法使用此方法发送args

然后我使用github.com/extrabacon/python-shell

我可以发送args但它不应该返回打印....

你能帮我拿到我的照片吗?

您可以在下面看到我的简短代码,它只是一个简单的代码,只是为了让它正常工作。

pythonShell.run

这里是python代码:

var pythonShell = require('python-shell');

app.post('/index/generator/',urlencodedParser, function (req,res){
  var options = {   
    mode: 'JSON',
    pythonOptions: ['-u'],
    scriptPath: './generator',
    args: ['hello','bye']
  };

  pythonShell.run('generator.py', options, function (err, results) {    
    if (err) throw err;
    console.log("Message %j ",results);
  });
})

1 个答案:

答案 0 :(得分:1)

您可以使用child_process,

  1. 使python文件可执行

    chmod +x generator.py

  2. 产生子进程

  3. ```

    const { spawn } = require('child_process');
    const ls = spawn('./generator.py', ['hello', 'world']);
    
    ls.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`);
    });
    
    ls.stderr.on('data', (data) => {
      console.log(`stderr: ${data}`);
    });
    

    ```

    然后使用process.send与父进程进行通信