What's a good way to exec a bunch of python code, like exec mycode
, and capture everything it prints to stdout into a string?
What does exec return in Python? Python exec() does not return a value; instead, it returns None. A string is parsed as Python statements, which are then executed and checked for any syntax errors. If there are no syntax errors, the parsed string is executed.
If you want to execute Python statements, you can use exec(string). For example, >>> my_code = 'print "Hello World!"' >>> exec(my_code) Hello World!
To execute dynamically generated Python code, use Python's exec function; to evaluate a dynamically generated Python expression, use Python's eval function. Beware: using these functions (or any of the below) with input from the user potentially allows the user to execute arbitrary code.
Try replacing the default sys.stdout, like in this snippet:
import sys
from StringIO import StringIO
buffer = StringIO()
sys.stdout = buffer
exec "print 'Hello, World!'"
#remember to restore the original stdout!
sys.stdout = sys.__stdout__
print buffer.getvalue()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With