Node.js 的 python 子脚本在完成时输出,而不是实时输出

2024-04-09

我是node.js 和socket.io 的新手,我正在尝试编写一个小型服务器,它将根据python 输出更新网页。

最终这将用于温度传感器,所以现在我有一个虚拟脚本,它每隔几秒打印一次温度值:

恒温器.py

import random, time
for x in range(10):
    print(str(random.randint(23,28))+" C")
    time.sleep(random.uniform(0.4,5))

这是服务器的精简版本:

Index.js

var sys   = require('sys'), 
    spawn = require('child_process').spawn, 
    thermostat = spawn('python', ["thermostat.py"]),
    app = require('express')(),
    http = require('http').Server(app),
    io = require('socket.io')(http);

thermostat.stdout.on('data', function (output) { 
    var temp = String(output);
    console.log(temp);
    io.sockets.emit('temp-update', { data: temp});
}); 

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
    });

最后是网页:

索引.html

<!doctype html>
<html>
    <head>
        <title>Live temperature</title>
        <link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    <body>
    <div id="liveTemp">Loading...</div>

    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io();
        socket.on('temp-update', function (msg) {
        $('#liveTemp').html(msg.data)
    });
    </script>

    </body>
</html>

问题是nodejs似乎一次接收所有温度值,而不是随机间隔获取10个温度值,我得到all脚本完成后一个长字符串中的值的列表:


您需要在 python 中禁用输出缓冲。这可以通过多种不同的方式完成,包括:

  • 设置PYTHONUNBUFFERED环境变量
  • 通过-u切换到Python可执行文件
  • Calling sys.stdout.flush()每次写入后(或print()在你的情况下)到标准输出
  • 对于 Python 3.3+ 你可以通过flush=true to print(): print('Hello World!', flush=True)

另外,在你的节点代码中,(即使你在 python 代码中休眠并且现在正在刷新标准输出)你真的不应该假设output在你的“数据”处理程序中thermostat.stdout总是只有一行。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Node.js 的 python 子脚本在完成时输出,而不是实时输出 的相关文章

随机推荐