Created
October 20, 2020 15:47
-
-
Save wrist/3424ca96e47640a58f94abd899028d85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""Observe the stdout redirected from sub thread to main thread through shared StringIO instance""" | |
import time | |
import contextlib | |
from concurrent.futures import ThreadPoolExecutor | |
from io import StringIO | |
import streamlit as st | |
def print_func(sec: int): | |
for i in range(sec): | |
print(f"{i} [sec] printed in sub thread\n") | |
time.sleep(1) | |
return "print finished" | |
def thread_func(sio: StringIO): | |
with contextlib.redirect_stdout(sio): | |
result = print_func(10) | |
return result | |
if __name__ == '__main__': | |
st.write("# thread test") | |
shared_sio = StringIO() | |
with ThreadPoolExecutor() as executor: | |
future = executor.submit(thread_func, shared_sio) | |
# observe shared_sio | |
placeholder = st.empty() | |
while future.running(): | |
placeholder.empty() | |
placeholder.write(shared_sio.getvalue()) | |
time.sleep(1) | |
placeholder.empty() | |
placeholder.write(shared_sio.getvalue()) | |
result = future.result() | |
st.write(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment