我正在使用一个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);
}
});
您将希望使用派生并捕获python子进程的标准输出。一旦达到十个值,就可以终止python进程。
不幸的是,您将不得不修改python程序来刷新stout。这是没有办法的。如果您不手动刷新stdout,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);
});
将它们放在同一个目录中,并确保获取用于演示的拆分模块。