如何使用 asyncio 在 Streamlit 中运行子进程并显示输出

以下示例使用 subprocess 运行命令并在 Streamlit 应用中显示输出。它使用 asyncio 异步运行子进程,使用 st.code() 显示输出。

注意,这不提供输出的实时显示。子进程先运行,只有在完成后,输出才显示在 Streamlit 应用中。

streamlit_subprocess_simple.py
import streamlit as st
import asyncio
import sys

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

    stdout, stderr = await process.communicate()
    return stdout.decode(), stderr.decode()

async def main():
    st.write("Running subprocess...")
    stdout, stderr = await run_subprocess()

    st.write("Subprocess output:")
    st.code(stdout)

    st.write("Subprocess errors:")
    st.code(stderr)

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

Check out similar posts by category: Streamlit, Python