如何列出导入的模块? [英] How to list imported modules?
本文介绍了如何列出导入的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何枚举所有导入的模块?
How to enumerate all imported modules?
例如我想从这段代码中得到 ['os', 'sys']
:
E.g. I would like to get ['os', 'sys']
from this code:
import os
import sys
推荐答案
import sys
sys.modules.keys()
获取当前模块的所有导入的近似值是检查 globals()
用于模块:
An approximation of getting all imports for the current module only would be to inspect globals()
for modules:
import types
def imports():
for name, val in globals().items():
if isinstance(val, types.ModuleType):
yield val.__name__
这不会返回本地导入或非模块导入,例如 from x import y
.请注意,这将返回 val.__name__
,因此如果您使用 import module as alias
,您将获得原始模块名称;如果您想要别名,请改为使用名称.
This won't return local imports, or non-module imports like from x import y
. Note that this returns val.__name__
so you get the original module name if you used import module as alias
; yield name instead if you want the alias.
这篇关于如何列出导入的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文