Streamlit:如何在 Web UI 上运行子进程并实时显示 stdout

此示例使用 asyncio 运行子进程并在 Streamlit Web UI 中实时显示其输出(当命令仍在运行时)。这对于长时间运行的进程很有用,你希望随着输出的到来而显示输出。

streamlit_subprocess_live_output.py
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


Check out similar posts by category: Streamlit, Python