测试sys.modules
字典中的模块名称:
import sys
modulename = 'datetime'
if modulename not in sys.modules:
print 'You have not imported the {} module'.format(modulename)
从文档中:
这是将模块名称映射到已经加载的模块的字典。
请注意,import
语句有两件事:
该表达式modulename not in sys.modules
测试步骤1是否已发生。测试步骤2的结果需要知道使用了什么确切的import
语句,因为它们设置了不同的名称来引用不同的对象:
# 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'])
这仅告诉您名称存在(已绑定),而不是名称是指特定模块还是该模块中的对象。sys.modules
如果您需要排除此后名称已完全设置为其他名称,则可以进一步自省该对象或测试该对象是否与所提供的对象相同。