【问题标题】:Logging script data with Node child_process使用 Node child_process 记录脚本数据
【发布时间】:2014-04-11 20:08:10
【问题描述】:

我正在使用一个循环运行并每秒输出一个新值的 python 脚本,并且只能通过按键盘上的enter 来停止。由于各种原因,python代码不应该被修改。

问:如何捕获循环脚本的前十个值,然后从 Node 中终止脚本?

我编写了下面的 Node 脚本,它将启动一个外部程序并记录输出;但是,这只适用于不在循环中运行的脚本。

var exec = require('child_process').exec;
var scriptCommand = "sudo python script.py"

exec(scriptCommand, function cb(error, stdout, stderr){
  console.log('stdout: ' + stdout);
  console.log('stderr: ' + stderr); 
  if (error !== null){
    console.log('exec error: ' + error);
  }
});

【问题讨论】:

    标签: node.js logging child-process


    【解决方案1】:

    您将要使用 spawn 并捕获 python 子进程的标准输出。一旦达到十个值,就可以终止 python 进程。

    不幸的是,您将不得不修改 python 程序以刷新 stout。没有办法解决这个问题。如果你不手动刷新标准输出,python 会,但只有在内部缓冲区填满之后(在我的示例代码中这需要一段时间)。

    这是一个完整的工作示例(捕获前三个值,然后终止 python 进程):

    pyscript.py

    #!/usr/bin/env python
    # python 2.7.4
    import time
    import sys
    
    i = 0
    while(True):
        time.sleep(1)
        print("hello " + str(i))
    
        # Important! This will flush the stdout buffer so node can use it
        # immediately. If you do not use this, node will see the data only after
        # python decides to flush it on it's own.
        sys.stdout.flush()
    
        i += 1
    

    script.js

    #!/usr/bin/env node
    "use strict";
    // node version 0.10.26
    
    var spawn = require('child_process').spawn
    , path = require('path')
    , split = require('split');
    
    // start the pyscript program
    var pyscript = spawn('python', [ path.join(__dirname, 'pyscript.py') ]);
    
    var pythonData = [];
    
    // Will get called every time the python program outputs a new line.
    // I'm using the split module (npm) to get back the results
    // on a line-by-line basis
    pyscript.stdout.pipe(split()).on('data', function(lineChunk) {
        // Kill the python process after we have three results (in our case, lines)
        if (pythonData.length >= 3) {
            return pyscript.kill();
        }
    
        console.log('python data:', lineChunk.toString());
        pythonData.push(lineChunk.toString());
    });
    
    // Will be called when the python process ends, or is killed
    pyscript.on('close', function(code) {
        console.log(pythonData);
    });
    

    将它们放在同一个目录中,并确保获取split 模块以使演示工作。

    【讨论】:

    • 优雅 - 谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 2015-11-05
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2021-09-27
    • 2011-04-12
    相关资源
    最近更新 更多