11

我有使用 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 的退出命令),我才会收到所有命令的输出。

4

3 回答 3

12

您需要刷新子进程中的输出。

可能您认为这没有必要,因为当测试并让输出发生在终端上时,库会自行刷新(例如,当一行完成时)。打印到管道时不会这样做(由于性能原因)。

冲洗自己:

#!/usr/bin/env python

import sys, time

while True:
  print "foo"
  sys.stdout.flush()
  time.sleep(2)
于 2013-09-17T12:01:12.383 回答
6

最好的方法是使用 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);
});
于 2014-10-12T12:31:03.547 回答
0

在我的情况下,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);
    });
于 2019-03-17T19:01:54.150 回答