我必须将文本从 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 pythonimport sysimport codecsif 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 filesifp.close()ofp.close()我必须用一个utf-8编码输入的读者,所以我使用sys.stdin,但似乎Node.js的写入子进程的时候stdin使用child.stdin.write(data + '\r\n');,这样不会被读取sys.stdin的for line in ifp:
1 回答
![?](http://img1.sycdn.imooc.com/545869510001a20b02200220-100-100.jpg)
三国纷争
TA贡献1804条经验 获得超7个赞
您需要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()
需要调用以确保写入的数据的最后一部分被刷新。它也具有指示子进程不会在此流上发送更多数据的效果。)
添加回答
举报
0/150
提交
取消