我正在编写一个 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)
该函数导入模块name
,可能使用给定的globals
and locals
确定如何在包上下文中解释名称。这fromlist
给出应从给定模块导入的对象或子模块的名称name
.
Source: https://docs.python.org/3/library/functions.html#__import_ 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()
这工作得很好,我只是想知道是否有可能有一种更惯用的方法来完成我们用这段代码所做的事情。
请注意,我特别不想使用鸡蛋或扩展点。这不是一个开源项目,我不希望有“插件”。重点是简化主要应用程序代码,并且无需在每次添加新命令模块时修改它。
See also: How do I import a module given the full path? https://stackoverflow.com/questions/67631