简体   繁体   English

从python-shell返回值作为响应

[英]return value from python-shell as response

I'm using python shell to run python on nodeJS. 我正在使用python shell在nodeJS上运行python。 I need to return python shell out put as the response. 我需要返回python shell作为响应。 but when i try to send the response it shows an error 但是当我尝试发送响应时,它显示了一个错误

Can't set headers after they are sent.

here is my code 这是我的代码

app.post('/therun', (req, res)=>{

    var pyshell = new PythonShell('hello.py');

    pyshell.on('message', function (message) {

       console.log(message); //value is correct
       res.send(message); //error here

      });

       res.send(message); //if i use here message undefined


});

How to slove this? 如何解决这个问题?

    app.post('/therun', (req, res)=>{

    var pyshell = new PythonShell('hello.py');
    var test={};

    pyshell.on('message', function (message) {

       console.log(message); //value is correct
       //res.send(message); //error here
      test=message;

      });
       console.log(test);
       res.send(message); //if i use here message undefined


});

Can you tell me the response on your console for the value of test ? 您能告诉我控制台上对test值的响应吗?

Instead of sending it as, 与其发送为

res.send(message); //error here

Can you please try sending the same with a status code given below? 您可以尝试使用下面给出的状态码发送邮件吗?

res.status(200).json({
  "message":message
})

Hope this helps! 希望这可以帮助!

You forgot to close the python shell (after pyshell.on()): 您忘记了关闭python shell(在pyshell.on()之后):

pyshell.end(function (err) {
  if (err) throw err;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM