【发布时间】:2016-11-24 16:58:19
【问题描述】:
我有一个 node.js 脚本,它启动一个 python 子进程并读取它的标准输出。只要 python 进程不尝试从标准输入读取,这就会起作用。那么父进程就不会从子进程那里得到任何东西。
我这里有 node.js 脚本和两个 python 测试用例:(如果你注释试图从标准输入读取的行,这两个例子都有效)
第一个孩子:
import sys
print('before')
for line in sys.stdin:
print(line)
print('after')
第二个孩子:
import sys
print('before')
while True:
line = sys.stdin.readline()
if line != '':
print(line)
else:
break
print('after')
家长:
const spawn = require('child_process').spawn;
let client = spawn('python', ['test1.py'], {cwd: '/tmp'});
client.stdout.on('data', (data) => {
console.log(data.toString());
});
client.stderr.on('data', (data) => {
console.log(data.toString());
});
client.on('close', () => {
console.log('close');
});
client.on('exit', () => {
console.log('exit');
});
client.on('disconnect', () => {
console.log('disconnect');
})
【问题讨论】:
-
我不知道 node.js,但从 python 的角度来看,写了一行,但由于它是一个管道,而不是一个 tty,它被缓冲等待更多数据。您可以立即发送
print('before', flush=True)。然后它等待数据......好吧......你需要发送数据。 -
flush=True技巧确实解决了这个问题。如果您将此作为答案发布,我会接受它:) -
在
node.js端使用const spawn = require('pty.js').spawn;之类的东西来解决这个问题可能会更好。这个问题讨论了拆分stdout/err 流*.com/questions/15339379/…。我很乐意提供答案……但我不确定它是否是最佳答案。 -
...输入错误。那是'pty.js'
标签: python node.js process stdout stdin