Skip to content

Instantly share code, notes, and snippets.

@tribela
Created August 17, 2015 02:52
Show Gist options
  • Save tribela/97181b6126cae006baff to your computer and use it in GitHub Desktop.
Save tribela/97181b6126cae006baff to your computer and use it in GitHub Desktop.
exec code safely on python
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