Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a block of python code with exec, capturing all its output?

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?

like image 250
Claudiu Avatar asked Feb 04 '11 23:02

Claudiu


People also ask

What does exec () return Python?

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.

How do I execute a string containing Python code in Python?

If you want to execute Python statements, you can use exec(string). For example, >>> my_code = 'print "Hello World!"' >>> exec(my_code) Hello World!

How do you run a dynamic code in Python?

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.


1 Answers

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()
like image 188
vrde Avatar answered Nov 08 '22 14:11

vrde