小编Mar*_*tin的帖子

Node.js 从 stdin 读取时无法读取 python 子进程 stdout

我有一个 node.js 脚本,它启动一个 python 子进程并读取它的标准输出。只要 python 进程不尝试从 stdin 读取数据,这种方法就有效。那么父进程就不会从子进程那里得到任何东西。

我这里有 node.js 脚本和两个 python 测试用例:(如果您注释尝试从 stdin 读取的行,这两个示例都有效)

第一个孩子:

import sys

print('before')

for line in sys.stdin:
    print(line)

print('after')
Run Code Online (Sandbox Code Playgroud)

第二个孩子:

import sys 

print('before')

while True:
    line = sys.stdin.readline()

    if line != '':
        print(line)
    else:
        break

print('after')
Run Code Online (Sandbox Code Playgroud)

家长:

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', …
Run Code Online (Sandbox Code Playgroud)

python stdin stdout process node.js

2
推荐指数
1
解决办法
2571
查看次数

标签 统计

node.js ×1

process ×1

python ×1

stdin ×1

stdout ×1