【发布时间】: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 格式的变量?
【问题讨论】: