python - Node.js Python 外壳 : while true loop not working

标签 python node.js

我用这个简单的 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/

相关文章:

python - Opsgenie powershell 警报帖子不起作用

python - 如何在与 input() 函数相同的行上打印一个字符串?

node.js - 恶梦循环法提取数据

javascript - Promise 拒绝因异常而暂停,但没有记录错误

node.js - 即使在 Webstorm 2018.3 中进行 Babel 配置后,Spread Operator 也会抛出 SyntaxError

python - 如何为早期版本的 python 构建 RPM?

Python-如何为字典中的值设置最大数量?

python - 结果为 append 到列表的多处理 for 循环

windows - 无需构建即可在 Windows 上获取 node-gyp 依赖模块

javascript - 如果 URL 的域错误,img.onerror() 似乎不会触发