I have a setup that looks as following:
from io import StringIO
from contextlib import redirect_stdout
f = StringIO()
with redirect_stdout(f):
exec("""'echo "test"'""")
s = f.getvalue()
print("return value:",s)
Is there a reason why the return value s does not contain "test"? How can I access this value?
exec
executes Python code; it's not an equivalent of os.system
.
What you are executing is the Python expression statement 'echo "test"'
, which simply evaluates to string. Expressions have values, but an expression statement ignores the value produced by the expression. Nothing is written to standard output in this case.
You want something like subprocess.check_output
:
>>> subprocess.check_output("""echo 'test'""", shell=True).decode().rstrip('\n')
'test'