首页 > 解决方案 > Python 子进程从 Node.js 父进程遍历标准输入

问题描述

我的Node.js父程序执行一个子Python进程并向其发送文本数据 - 请参阅此处了解实现。这工作正常,节点父进程将数据写入为:

child.stdin.setEncoding('utf-8');
child.stdin.write(data + '\r\n');
child.stdin.end();

Python 子进程回显它:

for line in sys.stdin:
    ofp.write(line)

并将数据返回给父级:

child.stdout.on('data', function (_data) {
    var data = Buffer.from(_data, 'utf-8').toString().trim();
    res += data;
});

我希望我的父进程在子进程中分叉一次child.stdin.write();,并在不关闭流的情况下进行后续调用。如果在父进程中我喜欢

setInterval(() => {
    child.stdin.write(data + '\r\n');
    child.stdin.end();
}, 1000);

Error [ERR_STREAM_WRITE_AFTER_END]: write after end由于end()调用,这将在第二次执行时导致错误。如果我省略了,child.stdin.end();我会得到任何输出。根据这里 sys.stdin.readline将逐行阅读直到Ctrl+D

def read_stdin():
    readline = sys.stdin.readline()
    while readline:
        yield readline
        readline = sys.stdin.readline()

for line in read_stdin():
    ofp.write(line)

另一种方法是

for line in iter(sys.stdin.readline, ''):
    print line

在这两种情况下,我都没有将数据返回给父节点进程。

标签: pythonnode.jspipe

解决方案


推荐阅读