How to run subprocess in streamlit using asyncio and display output
The following example runs a command using subprocess
and displays the output in a Streamlit app. It uses asyncio
to run the subprocess asynchronously and st.code()
to display the output.
Note that this does not provide a realtime display of the output. The subprocess is run first, and only after finishing, the output is displayed in the Streamlit app.
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())