Node.js Python-shell:while true loop not working

我有这个简单的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因为输出被pipe道化,因为它是pipe道的:

 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'); }); 

输出将是无缓冲的,所以不需要刷新标准输出。