Skip to content Skip to sidebar Skip to footer

Continuously Stream Output From Program In Python Using Websockets

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 lo

Solution 1:

One way of doing this is to use asyncio's create_subpocess_exec command. The Process instance returned here doesn't have an equivalent .poll() method, but you can still query for the returncode attribute as long as we create_task the process.wait()

import asyncio
import supbrocess


async def time(websocket, path):
    while True:
        command = 'myprogram'
        args = ['a', 'r', 'g', 's']
        process = await asyncio.create_subprocess_exec(command, *args, stdout=subprocess.PIPE)
        asyncio.create_task(process.wait()) # this coroutine sets the return code
        # Must check explicitly for None because successful return codes are usually 0
        while process.returncode is None:
            now = await process.stdout.read()
            if now:
                await websocket.send(now)
            await asyncio.sleep(0) # allow time for the wait task to complete otherwise this coroutine will always be busy
            # see: https://docs.python.org/3/library/asyncio-task.html#sleeping

Post a Comment for "Continuously Stream Output From Program In Python Using Websockets"