如何列出导入的模块?


152

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

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

import os
import sys

我不认为这是在本机Python可能的,但是这先前的问题可能会帮助:stackoverflow.com/questions/2572582/...
parent5446

6
有时(例如:with ipython --pylab)会在加载预定义模块的情况下启动python解释器。问题仍然存在,如何知道使用的别名o_O
yota

Answers:


182
import sys
sys.modules.keys()

仅获取当前模块的所有导入的一种近似方法是检查globals()模块:

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。如果要使用别名,请改为产生名称。


2
或者,您可以找到sys.modules与globals的交集,而根本不进行类型测试。
Marcin 2013年

当您重新定义导入模块的名称时,这是唯一返回完整模块名称的解决方案。例如,如果您这样做import numpy as np,它将返回numpy而另外两个建议将返回np
joelostblom 2015年

1
如果出于某种原因同时需要模块名称和别名,则可以在name变量中使用它。因此,要生成字符串,import numpy as np请执行类似于'import %s as %s' % (val.__name__, name)yield语句现在所在的位置。
安德烈·C·安徒生

38

找到的路口sys.modulesglobals

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

1
也许用frozenset这里代替?-这是我的1班轮:frozenset(imap(lambda name: modules[name], frozenset(modules) & frozenset(globals())))
AT

上面的解决方案不提取使用from命令导入的模块。例如,考虑一下from scipy.stats import norm。这并不告诉我norm模块已导入。如何将其整合到其中?
Ujjwal

@Ujjwal好吧,这些模块并没有被导入,只是它们的组件。如果您需要所有内容,则只需使用sys.modules。
Marcin

28

如果要从脚本外部执行此操作:

Python 2

from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script("myscript.py")
for name, mod in finder.modules.iteritems():
    print name

Python 3

from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script("myscript.py")
for name, mod in finder.modules.items():
    print(name)

这将打印myscript.py加载的所有模块。


1
对于Python 3,将print语句更改.iteritems().items()并将其括起来
cardamom

注意:当您处理名称空间时,它会崩溃:bugs.python.org/issue40350
mPrinC

本身已被窃取,它在我的计算机上具有204个依赖项。
吉穆特

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

8

假设您已导入数学并重新:

>>import math,re

现在看到相同的用途

>>print(dir())

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


6

实际上,它与以下软件配合得很好:

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

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


这并不能真正回答问题。
bergercookie

4

此代码列出了由模块导入的模块:

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从中导入的模块。


1

从@Lila窃取(由于未格式化,因此无法发表评论),这也显示了模块的/ path /:

#!/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或您拥有什么。警告,它很长!


0

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

>>> [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)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.