Skip to content

Instantly share code, notes, and snippets.

@synodriver
Created August 9, 2022 09:01
Show Gist options
  • Save synodriver/869d94d5ac76d9bb56ccab799c421f80 to your computer and use it in GitHub Desktop.
Save synodriver/869d94d5ac76d9bb56ccab799c421f80 to your computer and use it in GitHub Desktop.
py安全沙盒环境
def safe_eval(c):
allow_func = {"print": print, "input": input}
bytecode = compile(c, "", "eval")
for name in bytecode.co_names:
if name not in allow_func:
raise Exception(f"not allowed function: {name}")
return eval(bytecode, {"__builtins__": {}}, allow_func)
safe_eval("""
print(input('please input: '))
""")
# safe_eval("""round(1)""")
safe_eval('''print([sub_class for sub_class in (10).__class__.__base__.__subclasses__()])''')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment