【问题标题】:How does child_process spawn capture python output in real timechild_process spawn如何实时捕获python输出
【发布时间】:2021-04-05 18:16:33
【问题描述】:

我正在学习vscode插件开发,想知道spawn能否实时获取输出。

我运行以下代码。

        const { spawn } = require('child_process');
        const child = spawn('python', ['test.py'], { cwd: 'path' });
        child.stdout.on('data', (data: Uint8Array) => {
            console.log(data.toString());
        });
        child.stderr.on('data', (data: Uint8Array) => {
            console.log(data.toString());
        });
        child.on('close', (code: number) => {
            console.log(` ${code}`);

        });

test.py

import sys
import time

sys.stdout.write('stdout 1\n')
time.sleep(1)
sys.stderr.write('stderr 1\n')
time.sleep(2)
sys.stdout.write('stdout 2\n')
time.sleep(3)
sys.stderr.write('stderr 2\n')

输出

stderr 1
stderr 2

stdout 1
stdout 2
0

我想要的是能够按顺序获得输出。 我测试了捕获shell脚本的输出是正常的。

【问题讨论】:

    标签: javascript python python-3.x typescript visual-studio-code


    【解决方案1】:

    这是因为python的缓冲,只要调用python加上-u参数就行了

    【讨论】:

      猜你喜欢
      • 2021-10-31
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 2016-09-21
      • 1970-01-01
      相关资源
      最近更新 更多