Python child process loop over stdin from Node.js

2019-06-03 00:07发布

问题:

My Node.js parent program executes a child Python process and send to it text data - see here for the implementation. This works ok, the node parent process writes data as:

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

the Python child process echoes it back:

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

and it gets back the data to the parent:

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

I want my parent process to fork once the child process, and make subsequent calls the child.stdin.write(); without closing the stream. If in the parent process I do like

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

this will cause, at the second very execution a Error [ERR_STREAM_WRITE_AFTER_END]: write after end error, because of the end() call. While if I omits the child.stdin.end(); I will get any output. According to here sys.stdin.readline will read line-by-line until 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)

the other approach was

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

In both cases I get no data back to the parent Node process.