繁体   English   中英

无法从 node.js spawn 存储或发送 json output

[英]Cannot store or send json output from node.js spawn

我正在尝试使用以下代码来获得所需的 python output 并将其存储并将结果作为 http 响应从 Z3B2819DD4C249555FZ. 这是我的代码

这是 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"
      });
 });
}

但是 output 仅在控制台/内部生成方法中打印。 如果我从外部 spawn 方法访问 output 它显示为空。 如何将 python 代码中的 output 存储在某个变量中? 此外,如果我直接在 child.on('close') 中执行 res.send(),则结果字符串包含特殊字符,如 '\r'、'\n' 等......我该如何避免这种情况? I even tried using JSON.parse but it throws error finding unwanted token at position 0. Please if anyone can let me know how to get proper output in res.send() and also how to store output in variable even as JSON?

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

但是 output 仅在控制台/内部生成方法中打印。 如果我从外部 spawn 方法访问 output 它显示为空。 如何将 python 代码中的 output 存储在某个变量中?

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

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

此外,如果我直接在 child.on('close') 中执行 res.send() ,则生成的字符串包含特殊字符,如 '\r'、'\n' 等......我该如何避免这种情况

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

child.on("close", (code) => {
   output = output.replace(/\\"/g, '"');  //somewhat like regex ?

   return res.send({
        statusCode: 200,
        status: 'Success',
        data: output
      });
 });
}

暂无
暂无

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

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