I have two scripts as below but I can not modify foo.py I have wrote code in bar.py to capture output produced by foo.py so I can modify the output before outputting it to terminal.
But, capture does not work. What am I doing wrong?
foo.py
----
import sys
def some_func():
sys.stdout.write("hello")
sys.stdout.flush()
def foo():
some_func()
sys.exit(1)
this is my module I can modify:
bar.py
----
import io
from contextlib import redirect_stdout
from foo import foo
f = io.StringIO()
with redirect_stdout(f):
foo()
s = f.getvalue()
print(s)
EDIT:
final solution
import io
from contextlib import redirect_stdout
from foo import foo
def capture_output(func):
f = io.StringIO()
try:
with redirect_stdout(f):
func()
except SystemExit:
return f.getvalue()
capture_output(foo)