3

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
asked Sep 20, 2019 at 0:32
1
  • You must explain why you absolutely need to use exec(), as solutions that do not use exec are almost always more elegant than those that do. Commented Sep 20, 2019 at 1:00

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.