Continuously stream output from program in Python using Websockets

独自空忆成欢 提交于 2021-02-11 12:44:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!