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
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.
swap_stdout function in my answer as a context manager, but I see there is already one in the stdlib that does it.
execare almost always more elegant than those that do.