Node.js 从 stdin 读取时无法读取 python 子进程 stdout
Node.js can't read python subprocess stdout when it read from stdin
我有一个 node.js 脚本,它启动一个 python 子进程并读取它的标准输出。只要 python 进程不尝试从 stdin 读取,这就有效。然后 parent 进程不会从 child.
中得到任何东西
我这里有 node.js 脚本和两个 python 测试用例:(如果您评论尝试从标准输入读取的行,这两个示例都有效)
第一child:
import sys
print('before')
for line in sys.stdin:
print(line)
print('after')
第二个child:
import sys
print('before')
while True:
line = sys.stdin.readline()
if line != '':
print(line)
else:
break
print('after')
Parent:
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');
})
进程 stdout
可以是无缓冲的、行缓冲的或块缓冲的,具体取决于进程的启动方式。特别是,从控制台启动的程序是行缓冲的,而标准输出被重定向(到管道或文件)的程序是块缓冲的。这样做是为了有效地增加整个程序。人们希望立即看到东西,所以终端是行缓冲的,但其他程序和文件可以等待并在更大的块中获取东西,所以它们是块缓冲的。
您可以通过在每次写入时强制刷新数据来解决 python 方面的问题。您可以使用 print
语句或 sys.stdout
object 本身
来执行此操作
print('line 1', flush=True)
print('line 2')
print('line 3')
sys.stdout.flush()
您还可以通过模拟终端在 node.js 端修复它,基本上是欺骗程序认为它正在向用户显示。
const spawn = require('pty.js').spawn;
这更通用 - 您不需要 child 的合作来使其工作。但它可能会变得复杂。一些 child 进程获取有关附加 tty 的信息以执行更复杂的操作,例如创建菜单或颜色输出。但它通常是一个不错的选择。
我有一个 node.js 脚本,它启动一个 python 子进程并读取它的标准输出。只要 python 进程不尝试从 stdin 读取,这就有效。然后 parent 进程不会从 child.
中得到任何东西我这里有 node.js 脚本和两个 python 测试用例:(如果您评论尝试从标准输入读取的行,这两个示例都有效)
第一child:
import sys
print('before')
for line in sys.stdin:
print(line)
print('after')
第二个child:
import sys
print('before')
while True:
line = sys.stdin.readline()
if line != '':
print(line)
else:
break
print('after')
Parent:
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');
})
进程 stdout
可以是无缓冲的、行缓冲的或块缓冲的,具体取决于进程的启动方式。特别是,从控制台启动的程序是行缓冲的,而标准输出被重定向(到管道或文件)的程序是块缓冲的。这样做是为了有效地增加整个程序。人们希望立即看到东西,所以终端是行缓冲的,但其他程序和文件可以等待并在更大的块中获取东西,所以它们是块缓冲的。
您可以通过在每次写入时强制刷新数据来解决 python 方面的问题。您可以使用 print
语句或 sys.stdout
object 本身
print('line 1', flush=True)
print('line 2')
print('line 3')
sys.stdout.flush()
您还可以通过模拟终端在 node.js 端修复它,基本上是欺骗程序认为它正在向用户显示。
const spawn = require('pty.js').spawn;
这更通用 - 您不需要 child 的合作来使其工作。但它可能会变得复杂。一些 child 进程获取有关附加 tty 的信息以执行更复杂的操作,例如创建菜单或颜色输出。但它通常是一个不错的选择。