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

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.

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

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.