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

标签 python node.js socket.io buffer stdout

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

最后是网页:

Index.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 个温度值,我在脚本完成后得到一个长字符串中的所有值完成:

lots of temp values console output

最佳答案

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

  • 设置PYTHONUNBUFFERED环境变量
  • -u 开关传递给 python 可执行文件
  • 每次写入后调用 sys.stdout.flush()(或在您的情况下为 print())到标准输出
  • 对于 Python 3.3+,您可以将 flush=true 传递给 print():print('Hello World!', flush=True)

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

关于python - Node.js 的 python 子脚本在完成时输出,不是实时的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25607799/

相关文章:

reactjs - 从NextJS上的组件或API路由调用Socket IO实例

caching - Android Webview - 无法禁用缓存

internet-explorer-7 - IE7 中的 Socket.io Node.js 错误 - 拒绝访问

python - 根据 Pandas 中的外键减去多列

javascript - 我的第一个 Node.js 服务器:加载资源失败:net::ERR_INCOMPLETE_CHUNKED_ENCODING

node.js - 带有 Continuation-local-storage 的 NodeJS TransactionID

javascript - Node ffmpeg 以编程方式构建的命令列表(?)

python - 合并 Pandas 列(一对多)

python - 如何在 tf.keras 中使用 model.predict 预测单个图像

python - 根据其他行中的值删除行