Streamlit: How to run subprocess with live stdout display on web UI

This example uses asyncio to run a subprocess and display its output live in a Streamlit web UI (while the command is still running). This is useful for long-running processes where you want to show the output as it comes in.

import streamlit as st
import asyncio

async def run_subprocess():
    # Create placeholder for live output
    output_placeholder = st.empty()
    accumulated_output = []

    process = await asyncio.create_subprocess_exec(
        'ping', '-c', '10', '1.1.1.1',
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )

    # Read stdout stream
    while True:
        line = await process.stdout.readline()
        if not line:
            break
            
        line = line.decode().strip()
        accumulated_output.append(line)
        
        # Update display with all output so far
        output_placeholder.code('\n'.join(accumulated_output))
        
    # Get any remaining output and errors
    stdout, stderr = await process.communicate()
    if stderr:
        st.write("Subprocess errors:")
        st.code(stderr.decode())

async def main():
    st.write("Running subprocess...")
    await run_subprocess()

if __name__ == '__main__':
    asyncio.run(main())

Streamlit live stdout