您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何检查是否已导入python模块?

如何检查是否已导入python模块?

测试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如果您需要排除此后名称已完全设置为其他名称,则可以进一步自省该对象或测试该对象是否与所提供的对象相同。

python 2022/1/1 18:34:39 有217人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶