您将要使用 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 模块以使演示工作。