问题:如何列出导入的模块?

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

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

import os
import sys

How to enumerate all imported modules?

E.g. I would like to get ['os', 'sys'] from this code:

import os
import sys

回答 0

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

import sys
sys.modules.keys()

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__

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.


回答 1

找到的路口sys.modulesglobals

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

Find the intersection of sys.modules with globals:

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

回答 2

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

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加载的所有模块。

If you want to do this from outside the script:

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)

This will print all modules loaded by myscript.py.


回答 3

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

回答 4

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

>>import math,re

现在看到相同的用途

>>print(dir())

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

let say you’ve imported math and re:

>>import math,re

now to see the same use

>>print(dir())

If you run it before the import and after the import, one can see the difference.


回答 5

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

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

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

It’s actually working quite good with:

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

This will create a list with importable module names.


回答 6

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

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

This code lists modules imported by your module:

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]

It should be useful if you want to know what external modules to install on a new system to run your code, without the need to try again and again.

It won’t list the sys module or modules imported from it.


回答 7

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

Stealing from @Lila (couldn’t make a comment because of no formatting), this shows the module’s /path/, as well:

#!/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()

which produces:

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
...

.. suitable for grepping or what have you. Be warned, it’s long!


回答 8

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

>>> [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)

I like using a list comprehension in this case:

>>> [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)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。