Node.js 个子进程到 Python 个进程

Node.js child process to Python process

我必须将文本从 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 编码输入 reader 所以我使用 sys.stdin,但似乎 node.js 写入子进程 stdin 使用 child.stdin.write(data + '\r\n');,这不会被 for line in ifp:

中的 sys.stdin 读取

您需要在最终调用 child.stdin.write() 之后在 Node 程序中调用 child.stdin.end()。在调用 end() 之前,child.stdin 可写流会将写入的数据保存在缓冲区中,因此 Python 程序看不到它。有关详细信息,请参阅 https://nodejs.org/docs/latest-v8.x/api/stream.html#stream_buffering 中的 Buffering 讨论。

(如果您将大量数据写入 stdin,那么写入缓冲区最终会填满,累积的数据将自动刷新到 Python 程序。然后缓冲区将再次开始收集数据。需要调用 end() 来确保写入数据的最后部分被刷新。它还具有向子进程指示不再发送数据的效果流。)