正如@antont 指出的那样,一旦 Python 结果出现在标准输出上,就可以使用刷新机制轻松完成。
怎么做
我已经测试了 3 种方法:
-
在 Python 代码中,传递一个关键字参数来打印:
print('text', flush=True)
-
在 Python 代码中,使用显式刷新:
import sys
# Do this every time you want to flush
sys.stdout.flush()
-
调用 Python 可执行文件时,为其提供始终刷新的选项:
python -u scriptName.py
(请参阅下面的两个使用python-shell 和child_process 的示例。
Node.js 示例
这个例子的关键部分是pythonOptions: ['-u']中的'-u',如果你去掉这个选项,Python不会自动刷新(除非你使用上面的方法1或2)。
let PythonShellLibrary = require('python-shell');
let {PythonShell} = PythonShellLibrary;
let shell = new PythonShell('/home/user/showRandomWithSleep.py', {
// The '-u' tells Python to flush every time
pythonOptions: ['-u']
});
shell.on('message', function(message){
window.console.log('message', message);
window.console.log(new Date())
})
这个例子的关键部分是spawn(pythonExecutable, ['-u', myPythonScript])中的'-u',如果你去掉这个选项,Python不会自动刷新(除非你使用上面的方法1或2)。
var myPythonScript = "/home/user/showRandomWithSleep.py";
var pythonExecutable = "python";
var uint8arrayToString = function(data) {
return String.fromCharCode.apply(null, data);
};
const spawn = require('child_process').spawn;
// The '-u' tells Python to flush every time
const scriptExecution = spawn(pythonExecutable, ['-u', myPythonScript]);
scriptExecution.stdout.on('data', (data) => {
console.log(uint8arrayToString(data));
window.console.log(new Date())
});
showRandomWithSleep.py,上面例子中用到的python文件
from random import *
import time
for i in range(5):
print("showRandomWithSleep.py")
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
print(random())
time.sleep(random()*5)
注意
我测试了上面的例子,结果略有不同。
使用python-shell 时,每print() 行都会输出打印。但是,当使用child_process 时,打印内容以块的形式输出。我不知道为什么会这样。
链接