如何动态导入模块并将其名称作为字符串?
我正在编写一个将命令作为参数的 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
和locals
来确定如何在包上下文中解释该名称。fromlist
给出了应从name
给出的模块导入的对象或子模块的名称。来源:https://docs.python.org/3/library/ function.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()
这工作得很好,我只是想知道是否可能有一种更惯用的方法来完成我们用这段代码所做的事情。
请注意,我特别不想使用鸡蛋或扩展点。 这不是一个开源项目,我不希望有“插件”。 重点是简化主要应用程序代码,并且无需在每次添加新命令模块时修改它。
另请参阅: 如何在给定完整路径的情况下动态导入模块?
I'm writing a Python application that takes a command as an argument, for example:
$ python myapp.py command1
I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:
myapp/
__init__.py
commands/
__init__.py
command1.py
command2.py
foo.py
bar.py
So I want the application to find the available command modules at runtime and execute the appropriate one.
Python defines an __import__()
function, which takes a string for a module name:
__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__
So currently I have something like:
command = sys.argv[1]
try:
command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"])
except ImportError:
# Display error message
command_module.run()
This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.
Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.
See also: How can I import a module dynamically given the full path?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
对于早于 2.7/3.1 的 Python,这几乎就是您的做法。
对于较新版本,请参阅 Python 的
importlib.import_module
2 和 Python 3。或者使用
__import__
您可以通过执行以下操作导入模块列表:直接从 深入了解 Python。
With Python older than 2.7/3.1, that's pretty much how you do it.
For newer versions, see
importlib.import_module
for Python 2 and Python 3.Or using
__import__
you can import a list of modules by doing this:Ripped straight from Dive Into Python.
对于 Python 2.7 和 3.1 及更高版本,推荐方法是使用
importlib
模块:例如
The recommended way for Python 2.7 and 3.1 and later is to use
importlib
module:e.g.
正如前面提到的 imp 模块为您提供加载功能:
我之前使用过这些来执行类似的操作。
就我而言,我定义了一个特定的类,其中包含所需的已定义方法。
加载模块后,我将检查该类是否在模块中,然后创建该类的实例,如下所示:
As mentioned the imp module provides you loading functions:
I've used these before to perform something similar.
In my case I defined a specific class with defined methods that were required.
Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:
使用 importlib
导入源文件
这是一个稍作修改的示例 来自文档:
从这里开始,
module< /code> 将是代表
pluginX
模块的模块对象(与通过执行import pluginX
分配给pluginX
的内容相同)。 因此,要调用pluginX
中定义的hello
函数(不带参数),请使用module.hello()
。要获得
from
模块“导入”功能的效果,请将其存储在已加载模块的内存缓存中,然后执行相应的from
导入:
要导入包,调用
import_module
就足够了。 假设当前工作目录下有一个包文件夹pluginX
; 然后就做Using importlib
Importing a source file
Here is a slightly adapted example from the documentation:
From here,
module
will be a module object representing thepluginX
module (the same thing that would be assigned topluginX
by doingimport pluginX
). Thus, to call e.g. ahello
function (with no parameters) defined inpluginX
, usemodule.hello()
.To get the effect "importing" functionality
from
the module instead, store it in the in-memory cache of loaded modules, and then do the correspondingfrom
import:Importing a package
To import a package instead, calling
import_module
is sufficient. Suppose there is a package folderpluginX
in the current working directory; then just do使用 imp 模块,或更直接的
__import__()
函数。Use the imp module, or the more direct
__import__()
function.如果你想在本地使用它:
同样可以使用
globals()
If you want it in your locals:
same would work with
globals()
您可以使用
exec
:You can use
exec
:与 @monkut 的解决方案类似,但此处描述的可重用且容错 http:// stamat.wordpress.com/dynamic-module-import-in-python/:
Similar as @monkut 's solution but reusable and error tolerant described here http://stamat.wordpress.com/dynamic-module-import-in-python/:
下面的内容对我有用:
如果你想在 shell 脚本中导入:
The below piece worked for me:
if you want to import in shell-script:
以下内容对我有用:
它从文件夹“modus”加载模块。 这些模块有一个与模块名称同名的类。 例如,文件 modus/modu1.py 包含:
结果是动态加载的类“适配器”的列表。
The following worked for me:
It loads modules from the folder 'modus'. The modules have a single class with the same name as the module name. E.g. the file modus/modu1.py contains:
The result is a list of dynamically loaded classes "adapters".