首页 > 解决方案 > Node.js 子进程运行 python 代码没有响应

问题描述

我有一个 Express Node.js 应用程序,但我想运行 python 代码(发送数据和接收结果)但是当我使用邮递员测试它时仍在加载并且我没有任何响应。

我的 node.js 代码

    router.get('/name', callName);

function callName(req, res) {
    var exec = require("child_process").exec;
    var process = exec('python',["./hello.py",
                             req.query.firstname,
                             req.query.lastname
                          ] );
    process.stdout.on('data', function(error,data) {
      console.log('stderr: ', error);
        res.send(data.toString());
    } )
}

蟒蛇代码

import sys
# Takes first name and last name via command
# line arguments and then display them
print("Output from Python")
 print("First name: " + sys.argv[1])
 print("Last name: " + sys.argv[2])

# Save the script as hello.py

谢谢@nijm 我找到了解决方案

归根结底,我的代码是

router.get('/name', callName);

function callName(req, res) {
var exec = require("child_process").exec;
exec(`python uploads/hello.py ${req.query.firstname} ${req.query.lastname}`, (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});
}

蟒蛇代码

import sys
# Takes first name and last name via command
# line arguments and then display them
print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])

# Save the script as hello.py

标签: node.jspython-3.xexpress

解决方案


child_process.exec方法不接受命令参数作为数组(就像这样child_process.spawn做),试试这个(未经测试):

var exec = require("child_process").exec;
exec(`python ./hello.py ${req.query.firstname} ${req.query.lastname}`, (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

推荐阅读