Redirecting terminal output

Dear all,

I am trying to develop a streamlit app to pass arguments to a python function that will run locally on the user’s computer. The user selects the conditions for the function and my intention was to have a ‘Run’ button to launch the script.
However, I would also like to feed the terminal output into streamlit, so the user can have a single interface to interact with the script.

I realise this topic has been mentioned before but I have not found anything that fixes this issue.

Some details first :

  • the app will not be deployed and only runs locally
  • streamlit 1.29
  • python 3.10

Here’s an example that I tried based on an earlier answer (thread)

@contextmanager
def st_capture(output_func):
    with StringIO() as stdout, redirect_stdout(stdout):
        old_write = stdout.write
        def new_write(string):
            ret = old_write(string)
            output_func(stdout.getvalue())
            return ret
        stdout.write = new_write
        yield
  
output = st.empty()
if st.button('Run DockM8'):
    with st_capture(output.code):
        process = subprocess.Popen(command_list, text=True, bufsize=1, universal_newlines=True)

I can’t seem to find a way to redirect the output of Popen() to a streamlit object, I also tried using subprocess.PIPE and subprocess.run() to no avail.

For reference I found similar issues here and here2

Any help would be much appreciated, happy to provide more code/info if required.

Hi @Antoine_Lacour

Here’s a snippet for displaying the terminal output from one of the app that I created.

# Run the script file
result = subprocess.Popen(['bash', 'run.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = result.communicate()

# Display the terminal output
st.text('\n'.join(stdout.decode().split('\n')[1:][:-1]))

The terminal output is displayed as follows:

Hope this helps!