我正在处理一个在循环上运行并每秒输出一个新值的python脚本,并且只能通过按键盘上的enter
来停止。由于各种原因,不应更改python代码。
问:如何捕获循环脚本的前十个值然后从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);
}
});
答案 0 :(得分:1)
您将要使用spawn并捕获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);
});
将它们放在同一目录中,并确保抓住split模块以使演示工作。