为了账号安全,请及时绑定邮箱和手机立即绑定

Node.js 子进程到 Python 进程

Node.js 子进程到 Python 进程

守着星空守着你 2021-11-09 20:41:11
我必须将文本从 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 回答

?
三国纷争

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()需要调用以确保写入的数据的最后一部分被刷新。它也具有指示子进程不会在此流上发送更多数据的效果。)


查看完整回答
反对 回复 2021-11-09
  • 1 回答
  • 0 关注
  • 182 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信