I want to turn python output into string variable using exec()
Something like this is the goal:
code = "print(3)"
string = exec(code) # string should then equal 3
Sorry if this was repeated. I couldn't find the solution anywhere. Thanks
nassim
1,5811 gold badge16 silver badges28 bronze badges
1 Answer 1
Actually contextlib provides a context manager that capture the stdout of your code called redirect_stdout.
Here is an example:
import io
from contextlib import redirect_stdout
func_str = 'print(3)'
stdout = io.StringIO()
with redirect_stdout(stdout):
exec(func_str)
out = stdout.getvalue()
print(out, out.strip() == '3')
Output:
3
True
PS: The code is inspired from contextlib.redirect_stdout documentation code example.
answered Sep 20, 2019 at 0:49
Chiheb Nexus
9,2774 gold badges33 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
sleblanc
Nice find! I was thinking about writing my
swap_stdout function in my answer as a context manager, but I see there is already one in the stdlib that does it.lang-py
execare almost always more elegant than those that do.