我是 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 个温度值,我在脚本完成后得到一个长字符串中的所有值完成:
最佳答案
您需要在 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/