笔者需要根据命令行参数引入不同的包,原先一直使用exec
函数,例如
exec("import %s as model"%sys.argv[1])
但是如 Why doesn’t exec work in a function with a subfunction? 所述,exec
不易于子方程内使用。
参照 Dynamic module import in Python,使用__import__
内置,可以比较方便的于非global环境内使用,例如
model = __import__(sys.argv[1])
缺点是子方程内部不易使用from package_name import *
功能,如 How does one do the equivalent of “import * from module” with Python’s import function? 所述。
参考资料:
import,reload,import在python中的区别
Why doesn’t exec work in a function with a subfunction?
Dynamic module import in Python
How does one do the equivalent of “import * from module” with Python’s import function?