如何枚举所有导入的模块?

例如,我想从下面的代码中获取['os', 'sys']:

import os
import sys

当前回答

在这种情况下,我喜欢使用列表理解:

>>> [w for w in dir() if w == 'datetime' or w == 'sqlite3']
['datetime', 'sqlite3']

# To count modules of interest...
>>> count = [w for w in dir() if w == 'datetime' or w == 'sqlite3']
>>> len(count)
2

# To count all installed modules...
>>> count = dir()
>>> len(count)

其他回答

print [key for key in locals().keys()
       if isinstance(locals()[key], type(sys)) and not key.startswith('__')]

这里有很多扭曲的答案,其中一些在最新的Python 3.10中不能正常工作。获得脚本完全导入的模块,而不是内部__builtins__或子导入的最佳解决方案是使用以下方法:

# import os, sys, time, rlcompleter, readline
from types import ModuleType as MT
all = [k for k,v in globals().items() if type(v) is MT and not k.startswith('__')]
", ".join(all)

# 'os, sys, time, rlcompleter, readline'

上面的结果是受到@marcin的启发,它基本上是所有模块和全局变量的并集:

# import os, sys, time, rlcompleter, readline
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]
for i in allmodules: print (' {}\n'.format(i))

#<module 'time' (built-in)>
#<module 'os' from 'C:\\Python310\\lib\\os.py'>
#<module 'sys' (built-in)>
#<module 'readline' from 'C:\\Python310\\lib\\site-packages\\readline.py'>
#<module 'rlcompleter' from 'C:\\Python310\\lib\\rlcompleter.py'>

还要注意,导入的顺序也反映在第一个解决方案中,但没有反映在最后一个解决方案中。然而,在第二个解决方案中也给出了模块路径,这可能在调试中很有用。

PS.我不确定我在这里使用的词汇是正确的,所以如果我需要纠正,请做出评论。

找到sys的交点。带全局变量的模块:

import sys
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]

这段代码列出了你的模块导入的模块:

import sys
before = [str(m) for m in sys.modules]
import my_module
after = [str(m) for m in sys.modules]
print [m for m in after if not m in before]

如果您想知道在新系统上安装哪些外部模块来运行您的代码,而不需要一次又一次地尝试,那么它应该是有用的。

它不会列出从它导入的sys模块或其他模块。

假设你已经导入了math和re:

>>import math,re

现在来看看同样的用法

>>print(dir())

如果在导入之前和导入之后运行它,可以看到区别。