Created
August 17, 2015 02:52
-
-
Save tribela/97181b6126cae006baff to your computer and use it in GitHub Desktop.
exec code safely on python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from contextlib import closing | |
from StringIO import StringIO | |
def run(code): | |
with closing(StringIO()) as sout, closing(StringIO()) as serr: | |
sys.stdout = sout | |
sys.stderr = serr | |
exec code in {'__builtins__': {}}, {} | |
sys.stdout = sys.__stdout__ | |
sys.stderr = sys.__stderr__ | |
return sout.getvalue(), serr.getvalue() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment