我正在尝试在 HTML 页面上显示 python 脚本的连续输出,但是一旦脚本的整个执行完成,就会显示输出。我已经使用子进程来运行 python 脚本(test.py),当我独立执行 python 脚本时,我可以逐行看到输出,但是当我将它与 websockets 一起使用时,它不起作用。谁能帮我解决这个问题?
这是我的代码:
消费者.py
import os
import subprocess
from channels.generic.websocket import AsyncWebsocketConsumer
class MyAsyncWebsocketConsumer(AsyncWebsocketConsumer):
async def connect(self):
print("Websocket connected")
print("Channel name...", self.channel_name)
print("Channel layer...", self.channel_layer)
await self.channel_layer.group_add('programmers', self.channel_name)
await self.accept()
async def receive(self, text_data=None, bytes_data=None):
print("Message received from the client", text_data)
current_dir = os.getcwd()
script = current_dir + '/' + 'test.py'
try:
p = subprocess.Popen(['python', script], stdout=subprocess.PIPE, bufsize=3)
for line in iter(p.stdout.readline, b''):
line = line.decode("utf-8").strip()
await self.send(text_data=line)
except subprocess.CalledProcessError as e:
print(e)
async def disconnect(self, code):
print("Websocket disconnected", code)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h3>Count Page</h3>
<textarea id="chat-log" cols="100" rows="20">
</textarea><br>
<input type="button" value="Submit" id="script-run-submit">
<script>
var ws = new WebSocket('ws://127.0.0.1:8000/ws/awsc/')
ws.onopen = function() {
console.log("Websocket connection opened")
}
ws.onmessage = function(event) {
console.log("Message received from the server", event)
data = event['data']
document.querySelector('#chat-log').value += (data + '\n')
}
ws.onerror = function(event) {
console.log("Websocket error occurred", event)
}
ws.onclose = function(event) {
console.log("Websocket connection close", event)
}
document.getElementById('script-run-submit').onclick = function (event) {
console.log("This function is executed")
ws.send(JSON.stringify({ 'msg' : 'Trigger the script' }))
}
</script>
</body>
</html>
期待
脚本输出应该在HTML页面中逐行显示
实际产量
脚本的所有输出一次显示在 HTML 页面中