I'm using the InteractiveInterpreter to execute code that has delays in it (see below). I'd like to capture the output from stdout
as the output is written. I'm currently using contextlib
to redirect stdout
along with StringIO
to buffer the output:
code = """import time
for i in range(3):
print(i)
time.sleep(1)"""
f = io.StringIO()
inter = InteractiveInterpreter()
with redirect_stdout(f):
inter.runcode(code)
out = f.getvalue()
print(out)
Naturally, since runcode
runs synchronously, the output is only available after the code finishes executing. I'd like to capture the output as it becomes available and do something with it (this code is running in a gRPC environment, so yielding the output in real time).
My initial thought was to wrap the running of the code and reading the output in two separate asyncio
coroutines and somehow have stdout
write to a stream and have the other task read from that stream.
Is the async approach feasible/reasonable? Any other suggestions? Thanks.