Last active
August 29, 2015 14:04
-
-
Save gregglind/1642f26521bd470e7a07 to your computer and use it in GitHub Desktop.
Eval, Exec, Safeguarding in python
This file contains 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
# from: http://effbot.org/zone/librarybook-core-eval.htm | |
print eval("__import__('os').remove('file')", {"__builtins__": {}}) # in particular, one has to kill or safeguard __import__ | |
# PyRun_SimpleStringFlags | |
https://github.com/python-git/python/blob/715a6e5035bb21ac49382772076ec4c630d6e960/Modules/main.c#L284 | |
https://github.com/python-git/python/blob/715a6e5035bb21ac49382772076ec4c630d6e960/Python/pythonrun.c#L949 | |
https://github.com/python-git/python/blob/715a6e5035bb21ac49382772076ec4c630d6e960/Python/pythonrun.c#L1286 | |
# is this enough? | |
exec compile(ast.parse("print 1"),'<string>','exec') | |
https://docs.python.org/2/c-api/veryhigh.html | |
# http://lucumr.pocoo.org/2011/2/1/exec-in-python/ | |
exec compile(ast.parse("""print a; print 1 | |
for k in range(5): | |
print 'abcdefg'[k] | |
"""),'string','exec') | |
# execute in new namespace? | |
>>> code = compile('a = 1 + 2', '<string>', 'exec') | |
>>> ns = {} | |
>>> exec code in ns | |
>>> print ns['a'] | |
3 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment