我用这个简单的 Python
脚本每秒打印一条消息:
#!/usr/bin/python
import time
while True:
print u"Message"
time.sleep(1)
我正在尝试使用 python-shell
将具有上述结构的第三方 Python 脚本与 Node.js
集成.
我正在使用这个 JS 脚本从 Python 脚本获取所有消息:
var PythonShell = require('python-shell');
var options = {
scriptPath: './'
};
var pyshell = new PythonShell('test.py',options);
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err) throw err;
console.log('finished');
});
但似乎是 Python 中的 while True
导致未调用 on-event。我该如何解决这个问题?我可以将 Python
脚本中的循环更改为与 python-shell
兼容的内容吗?
最佳答案
您需要刷新 sys.stdout
因为输出是缓冲的,因为它是管道传输的:
import time
import sys
while True:
print u"Message"
sys.stdout.flush()
time.sleep(1)
刷新后您将立即收到输出:
$ nodejs n.js
Message
Message
Message
.....
启动 shell 时,您可以将缓冲设置为行缓冲或无缓冲,但我对 nodejs 不是很熟悉。
实际上有一种方法可以设置 -u
标志以使用 pythonOptions
标志获得无缓冲输出:
var PythonShell = require('python-shell');
var pyshell = new PythonShell('test.py',{scriptPath:"./", pythonOptions: ['-u']});
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err) throw err;
console.log('finished');
});
输出将是无缓冲的,因此无需刷新标准输出。
关于python - Node.js Python 外壳 : while true loop not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29196440/