Node.js子进程到Python进程
我必须将node.js子进程中的文本发送到python进程。我的虚拟节点客户端看起来像
var resolve = require('path').resolve;
var spawn = require('child_process').spawn;
data = "lorem ipsum"
var child = spawn('master.py', []);
var res = '';
child.stdout.on('data', function (_data) {
try {
var data = Buffer.from(_data, 'utf-8').toString();
res += data;
} catch (error) {
console.error(error);
}
});
child.stdout.on('exit', function (_) {
console.log("EXIT:", res);
});
child.stdout.on('end', function (_) {
console.log("END:", res);
});
child.on('error', function (error) {
console.error(error);
});
child.stdout.pipe(process.stdout);
child.stdin.setEncoding('utf-8');
child.stdin.write(data + '\r\n');
而Python进程master.py
是
#!/usr/bin/env python
import sys
import codecs
if sys.version_info[0] >= 3:
ifp = codecs.getreader('utf8')(sys.stdin.buffer)
else:
ifp = codecs.getreader('utf8')(sys.stdin)
if sys.version_info[0] >= 3:
ofp = codecs.getwriter('utf8')(sys.stdout.buffer)
else:
ofp = codecs.getwriter('utf8')(sys.stdout)
for line in ifp:
tline = "<<<<<" + line + ">>>>>"
ofp.write(tline)
# close files
ifp.close()
ofp.close()
我必须使用utf-8
编码输入阅读器,所以我使用sys.stdin
,但似乎当node.js使用stdin
写入子进程child.stdin.write(data + '\r\n');
时,sys.stdin
中的for line in ifp:
将无法读取
在最后调用child.stdin.end()
之后,你需要在Node程序中调用child.stdin.write()
。在调用end()
之前,child.stdin
可写流将把写入的数据保存在缓冲区中,因此Python程序将无法看到它。有关详细信息,请参阅https://nodejs/docs/latest-v8.x/api/stream.html#stream_buffering中的缓冲讨论。
(如果你将大量数据写入stdin
,那么写缓冲区最终将填充到累积数据将自动刷新到Python程序的位置。缓冲区将再次开始收集数据。需要进行end()
调用确保写入数据的最后部分被刷新。它还具有向子进程指示在该流上不再发送数据的效果。)