我正在编写一个将命令作为参数的 Python 应用程序,例如:
$ python myapp.py command1
我希望应用程序是可扩展的,也就是说,能够添加实现新命令的新模块,而无需更改主应用程序源。这棵树看起来像:
myapp/
__init__.py
commands/
__init__.py
command1.py
command2.py
foo.py
bar.py
所以我希望应用程序在运行时找到可用的命令模块并执行适当的命令模块。
Python 定义了一个 __import__()
函数,该函数采用字符串作为模块名称:
__import__(name, globals=None, locals=None, fromlist=(), level=0)
The function imports the module
name
, potentially using the givenglobals
andlocals
to determine how to interpret the name in a package context. Thefromlist
gives the names of objects or submodules that should be imported from the module given byname
.Source: https://docs.python.org/3/library/functions.html#__import__
所以目前我有这样的东西:
command = sys.argv[1]
try:
command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"])
except ImportError:
# Display error message
command_module.run()
这工作得很好,我只是想知道是否有可能有更惯用的方法来完成我们用这段代码所做的事情。
请注意,我特别不想使用鸡蛋或扩展点。这不是一个开源项目,我不希望有“插件”。重点是简化主应用程序代码,并且无需每次添加新命令模块时都需要修改它。
<小时/>最佳答案
对于 2.7/3.1 之前的 Python,这几乎就是你的做法。
对于较新版本,请参阅 Python 2 的 importlib.import_module
和 Python 3 .
或者使用__import__
,您可以通过执行以下操作导入模块列表:
>>> moduleNames = ['sys', 'os', 're', 'unittest']
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)
直接从 Dive Into Python 盗取.
关于python - 如何动态导入模块并将其名称作为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60021636/