问题
I would like to create a websocket which will continuosly stream output from the program to the HTML webpage.
Process that my program executes takes 2 minutes to complete and it logs the outputs while it executes. Right now, my code updates the webpage everytime the program finishes executing and then displays all the logs on the webpage at once. I would like to continuosly update my webpage, i.e.: stream the output in realtime. My server code looks like this:
import nest_asyncio
nest_asyncio.apply()
import websockets
import subprocess
async def time(websocket, path):
while True:
command = ['myprogram', 'args']
process = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True, bufsize=-1)
now = process.stdout.read()
await websocket.send(now)
start_server = websockets.serve(time, "127.0.0.1", 5670)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
And my client side looks like this:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket</title>
</head>
<body>
<script>
var ws = new WebSocket("ws://127.0.0.1:5670/"),
messages = document.createElement('ul');
ws.onmessage = function (event) {
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode(event.data);
message.appendChild(content);
messages.appendChild(message);
};
document.body.appendChild(messages);
</script>
</body>
</html>
Any ideas on how this can be done?
来源:https://stackoverflow.com/questions/64611848/continuously-stream-output-from-program-in-python-using-websockets