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

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

import os
import sys

当前回答

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

>>import math,re

现在来看看同样的用法

>>print(dir())

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

其他回答

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

>>> [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('__')]

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

>>import math,re

现在来看看同样的用法

>>print(dir())

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

它实际上工作得很好:

import sys
mods = [m.__name__ for m in sys.modules.values() if m]

这将创建一个包含可导入模块名称的列表。

从@Lila(由于没有格式,无法发表评论)中窃取,这也显示了模块的/路径/:

#!/usr/bin/env python
import sys
from modulefinder import ModuleFinder
finder = ModuleFinder()
# Pass the name of the python file of interest
finder.run_script(sys.argv[1])
# This is what's different from @Lila's script
finder.report()

生产:

Name                      File
----                      ----

...
m token                     /opt/rh/rh-python35/root/usr/lib64/python3.5/token.py
m tokenize                  /opt/rh/rh-python35/root/usr/lib64/python3.5/tokenize.py
m traceback                 /opt/rh/rh-python35/root/usr/lib64/python3.5/traceback.py
...

. .适合grepping之类的。注意,它很长!