Node.js Python-shell:while循环不起作用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Node.js Python-shell:while循环不起作用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1528字,纯文字阅读大概需要3分钟。
内容图文
![Node.js Python-shell:while循环不起作用](/upload/InfoBanner/zyjiaocheng/954/4f1ef96a380443978c5cd6cee2d52deb.jpg)
我有这个简单的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');
});
输出将是无缓冲的,因此不需要刷新标准输出.
内容总结
以上是互联网集市为您收集整理的Node.js Python-shell:while循环不起作用全部内容,希望文章能够帮你解决Node.js Python-shell:while循环不起作用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。