我必须将文本从 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()
在最终调用child.stdin.write()
. 在end()
调用之前,child.stdin
可写流会将写入的数据保存在缓冲区中,因此 Python 程序不会看到它。有关详细信息,请参阅https://nodejs.org/docs/latest-v8.x/api/stream.html#stream_buffering 中的缓冲讨论。
(如果您写入大量数据,stdin
则写入缓冲区最终将填充到累积数据将自动刷新到 Python 程序的点。然后缓冲区将再次开始收集数据。end()
需要调用以确保写入的数据的最后一部分被刷新。它也有指示子进程不会在此流上发送更多数据的效果。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句