-1

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?

Yes
  • 339
  • 3
  • 19

2 Answers2

1

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'
chepner
  • 497,756
  • 71
  • 530
  • 681
0

First argument to exec should be

The source may be a string representing one or more Python statements
or a code object as returned by compile()

you did

exec("""'echo "test"'""")

i.e. delivered to exec something which is not valid python statement(s).

Daweo
  • 31,313
  • 3
  • 12
  • 25