Skip to content

Instantly share code, notes, and snippets.

@tristan2077
Last active July 19, 2019 07:49
Show Gist options
  • Save tristan2077/ff630165fb0583429ea66a3d02f98b6f to your computer and use it in GitHub Desktop.
Save tristan2077/ff630165fb0583429ea66a3d02f98b6f to your computer and use it in GitHub Desktop.
一种动态运行代码的方法
import importlib
func_text = """
def add(a,b):
return a + b
"""
with open('func.py', 'w') as f:
f.writelines(func_text)
try:
model = importlib.import_module("func")
f = getattr(model, "add")
print(f(1, 2))
except Exception as e:
print(f"编译错误:{e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment