我用这个简单的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事件没有被调用。我该如何解决这个问题?我可以将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');
});
输出将不缓冲,因此不需要刷新stdout。