簡體   English   中英

以流動模式流式傳輸子進程輸出

[英]Stream child process output in flowing mode

我有使用Python編寫的自定義命令行,它使用“print”語句打印其輸出。 我通過生成子進程並使用child.stdin.write方法向它發送命令從Node.js中使用它。 這是來源:

var childProcess = require('child_process'),
    spawn = childProcess.spawn;

var child = spawn('./custom_cli', ['argument_1', 'argument_2']);

child.stdout.on('data', function (d) {
  console.log('out: ' + d);
});

child.stderr.on('data', function (d) {
  console.log('err: ' + d);
});

//execute first command after 1sec
setTimeout(function () {
  child.stdin.write('some_command' + '\n');
}, 1000);

//execute "quit" command after 2sec
//to terminate the command line
setTimeout(function () {
  child.stdin.write('quit' + '\n');
}, 2000);

現在問題是我沒有在流動模式下接收輸出。 我希望在打印后立即從子進程獲取輸出,但只有在子進程終止時才會收到所有命令的輸出(使用自定義cli的quit命令)。

您需要刷新子進程中的輸出。

可能您認為這不是必需的,因為在測試並讓輸出發生在終端上時,庫會自行刷新(例如,當線路完成時)。 當打印進入管道時(由於性能原因),不會這樣做。

自己動手:

#!/usr/bin/env python

import sys, time

while True:
  print "foo"
  sys.stdout.flush()
  time.sleep(2)

最好的方法是使用無緩沖模式的python標准輸出。 它將強制python將輸出寫入輸出流而無需刷新自己。

例如:

var spawn = require('child_process').spawn,
child = spawn('python',['-u', 'myscript.py']); // Or in custom_cli add python -u myscript.py

child.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
});

child.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
});

在我的Python情況下,我使用sys.stdin.readline並產生最后一行:

def read_stdin():
    '''
        read standard input
        yeld next line
    '''
    try:
        readline = sys.stdin.readline()
        while readline:
            yield readline
            readline = sys.stdin.readline()
    except:
        # LP: avoid to exit(1) at stdin end
        pass

 for line in read_stdin():
     out = process(line)
     ofp.write(out)
     sys.stdout.flush()

Node.js

var child = spawn(binpath, args);

    // register child process signals
    child.stdout.on('data', function (_data) {
        var data = Buffer.from(_data, 'utf-8').toString().trim();
        console.log(data);
    });
    child.stderr.on('data', function (data) {
        console.warn('pid:%s stderr:%s', child.pid, data);
    });
    child.stdout.on('exit', function (_) {
        console.warn('pid:%s exit', child.pid);
    });
    child.stdout.on('end', function (_) {
        console.warn('pid:%s ended', child.pid);
    });
    child.on('error', function (error) {
        console.error(error);
    });
    child.on('close', (code, signal) => { // called after `end`
        console.warn('pid:%s terminated with code:%d due to receipt of signal:%s with ', child.pid, code, signal);
    });
    child.on('uncaughtException', function (error) {
        console.warn('pid:%s terminated due to receipt of error:%s', child.pid, error);
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM