【问题标题】:Cannot store or send json output from node.js spawn无法从 node.js spawn 存储或发送 json 输出
【发布时间】:2021-04-25 18:09:09
【问题描述】:

我正在尝试使用以下代码来获取所需的 python 输出并将其存储,并将结果作为来自 Node.js 的 http 响应发送。这是我的代码

这是python test.py 文件

import sys

print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])

这是 Node.js 生成方法

testRoute: async(req, res, next) => {

var output="";

var child = spawn('python', [`${process.cwd()}/pyCodes/test.py`,
   'Itachi',
   'Uchiha'
 ]);

child.stdout.setEncoding('utf8');
await child.stdout.on('data', (data) => {
   data = data.toString();
   output += data;
});

 child.stderr.on("data", (data) => {
    data = data.toString();
    output += data;
  });

child.on("error", (error) => {
  error = error.toString();
  output += error;
});

 child.stderr.pipe(process.stderr);

 cosnsole.log('output: ', output) // this shows output as empty
 
child.on("close", (code) => {
   return res.send({
        statusCode: 200,
        status: 'Success',
        data: output, // the output is like this : "Output from Python\r\nFirst name: Itachi\r\nLast name: Uchiha\r\n"
      });
 });
}

但输出仅在控制台/内部 spawn 方法中打印。如果我从外部 spawn 方法访问输出,它显示为空。如何将 python 代码的输出存储在某个变量中?另外,如果我直接在 child.on('close') 中执行 res.send() ,则生成的字符串包含特殊字符,如 '\r'、'\n' 等......我该如何避免这种情况?我什至尝试使用 JSON.parse 但它会在位置 0 找到不需要的令牌时抛出错误。请如果有人可以让我知道如何在 res.send() 中获得正确的输出,以及如何将输出存储为 JSON 格式的变量?

【问题讨论】:

    标签: python node.js spawn


    【解决方案1】:

    我不认为有任何这样的方法可以做到这一点。你所能做的就是将你从 spawn 获得的 python 代码的结果传递给另一个路由,或者通过 http 响应返回它,或者将它传递给另一个函数。

    【讨论】:

      【解决方案2】:

      但输出仅在控制台/内部 spawn 方法中打印。如果我 从显示为空的外部 spawn 方法访问输出。我怎样才能 将 python 代码的输出存储在某个变量中?

      你不能。由于 spawn 方法是异步运行的。一旦收到关闭事件触发器,它就会打印或播放数据。所以你的代码必须与行为保持一致。

      child.on("close", (code) => {
         console.log("output") 
      }
      

      另外,如果我在 child.on('close') 中直接执行 res.send() 结果字符串包含特殊字符,如 '\r'、'\n' 等...如何 我可以避免吗

      您可以使用正则表达式从最终字符串中删除特殊/转义字符。 example

      child.on("close", (code) => {
         output = output.replace(/\\"/g, '"');  //somewhat like regex ?
      
         return res.send({
              statusCode: 200,
              status: 'Success',
              data: output
            });
       });
      }
      

      【讨论】:

      • 那么除了spawn之外,没有其他方法可以将输出存储在python代码的变量中吗?
      • 你需要运行python“localy”吗?您可以使用框架(例如flask)将其作为服务器,并让您的node.js API 使用REST 与python 通信(发送和接收JSON)。
      猜你喜欢
      • 2021-10-31
      • 2014-11-13
      • 1970-01-01
      • 2020-05-04
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多