如何检查python模块是否已导入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30483246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a python module has been imported?
提问by yuval
How do I check if I imported a module somewhere in the code?
如何检查我是否在代码中的某处导入了模块?
if not has_imported("somemodule"):
print('you have not imported somemodule')
The reason that I would like to check if I already imported a module is because I have a module that I don't want to import because sometimes it messes up my program.
我想检查是否已经导入了一个模块的原因是因为我有一个不想导入的模块,因为有时它会弄乱我的程序。
采纳答案by Martijn Pieters
Test for the module name in the sys.modules
dictionary:
测试sys.modules
字典中的模块名称:
import sys
modulename = 'datetime'
if modulename not in sys.modules:
print 'You have not imported the {} module'.format(modulename)
From the documenation:
从文档中:
This is a dictionary that maps module names to modules which have already been loaded.
这是一个将模块名称映射到已加载模块的字典。
Note that an import
statementdoes two things:
请注意,import
语句有两件事:
- if the module has never been imported before (== not present in
sys.modules
), then it is loaded and added tosys.modules
. - Bind 1 or more names in the current namespace that reference the module object or to objects that are members of the module namespace.
- 如果模块之前从未导入过(== 中不存在
sys.modules
),则将其加载并添加到sys.modules
. - 将当前命名空间中的 1 个或多个名称绑定到引用模块对象或作为模块命名空间成员的对象。
The expression modulename not in sys.modules
tests if step 1 has taken place. Testing for the result of step 2 requires knowing what exact import
statement was used as they set different names to reference different objects:
该表达式modulename not in sys.modules
测试步骤 1 是否已发生。测试第 2 步的结果需要知道使用了什么确切的import
语句,因为它们设置了不同的名称来引用不同的对象:
import modulename
setsmodulename = sys.modules['modulename']
import packagename.nestedmodule
setspackagename = sys.modules['packagename']
(no matter how many addional levels you add)import modulename as altname
setsaltname = sys.module['modulename']
import packagename.nestedmodule as altname
setsaltname = sys.modules['packagename.nestedmodule']
from somemodule import objectname
setsobjectname = sys.modules['somemodule'].objectname
from packagename import nestedmodulename
setsnestedmodulename = sys.modules['packagename.nestedmodulename']
(only when there was no object namednestedmodulename
in thepackagename
namespace before this import, an additional name for the nested module is added to the parent package namespace at this point)from somemodule import objectname as altname
setsaltname = sys.modules['somemodule'].objectname
from packagename import nestedmodulename as altname
setsaltname = sys.modules['packagename.nestedmodulename']
(only when there was no object namednestedmodulename
in thepackagename
namespace before this import, an additional name for the nested module is added to the parent package namespace at this point)
import modulename
套modulename = sys.modules['modulename']
import packagename.nestedmodule
设置packagename = sys.modules['packagename']
(无论您添加多少附加级别)import modulename as altname
套altname = sys.module['modulename']
import packagename.nestedmodule as altname
套altname = sys.modules['packagename.nestedmodule']
from somemodule import objectname
套objectname = sys.modules['somemodule'].objectname
from packagename import nestedmodulename
集nestedmodulename = sys.modules['packagename.nestedmodulename']
(仅当没有指定的对象nestedmodulename
在packagename
该导入之前命名空间,嵌套模块附加的名称被添加到父包命名空间在这一点)from somemodule import objectname as altname
套altname = sys.modules['somemodule'].objectname
from packagename import nestedmodulename as altname
集altname = sys.modules['packagename.nestedmodulename']
(仅当没有指定的对象nestedmodulename
在packagename
该导入之前命名空间,嵌套模块附加的名称被添加到父包命名空间在这一点)
You can test if the name to which the imported object was bound exists in a given namespace:
您可以测试导入对象绑定的名称是否存在于给定的命名空间中:
# is this name visible in the current scope:
'importedname' in dir()
# or, is this a name in the globals of the current module:
'importedname' in globals()
# or, does the name exist in the namespace of another module:
'importedname' in globals(sys.modules['somemodule'])
This only tells you of the name exists (has been bound), not if it refers to a specific module or object from that module. You could further introspect that object or test if it's the same object as what's available in sys.modules
, if you need to rule out that the name has been set to something else entirely since then.
这只会告诉您名称存在(已绑定),而不是它是否引用特定模块或来自该模块的对象。您可以进一步内省该对象或测试它是否与 中可用的对象相同sys.modules
,如果您需要排除该名称从那时起已完全设置为其他内容。
回答by Haresh Shyara
use sys.modules to test if a module has been imported (I'm using unicodedata as an example):
使用 sys.modules 测试模块是否已导入(我以 unicodedata 为例):
>>> import sys
>>> 'unicodedata' in sys.modules
False
>>> import unicodedata
>>> 'unicodedata' in sys.modules
True
回答by rundekugel
if "sys" not in dir():
print("sys not imported!")
回答by morvan68
To the sys.modules answers accepted, I'd add one caveat to be careful about renaming modules on import:
对于接受的 sys.modules 答案,我会添加一个警告,以注意在导入时重命名模块:
>>> import sys
>>> import datetime as dt
>>> 'dt' in sys.modules
False
>>> 'datetime' in sys.modules
True
回答by HansW
sys.modules
contains all modules used anywhere in the current instance of the interpreter and so shows up if imported in any other Python module.
sys.modules
包含在解释器当前实例中任何地方使用的所有模块,因此如果在任何其他 Python 模块中导入,则会显示。
dir()
checks whether the name was defined in the current namespace.
dir()
检查名称是否在当前命名空间中定义。
The combination of the 2 is more safe than each separate and works as long you didn't define a copy
yourself.
2 的组合比每个单独的组合更安全,只要您没有定义copy
自己就可以工作。
if ('copy' in sys.modules) and ('copy' in dir()):