我有这个简单的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中的True会导致事件未被调用.我怎么解决这个问题?我可以将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.

实际上有一种方法可以使用pythonOptions标志设置-u标志以获得无缓冲的输出:

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

相关文章推荐

添加新评论,含*的栏目为必填