Last active
July 19, 2019 07:49
-
-
Save tristan2077/ff630165fb0583429ea66a3d02f98b6f to your computer and use it in GitHub Desktop.
一种动态运行代码的方法
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
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