Python 如何列出导入的模块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4858100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to list imported modules?
提问by alex2k8
How to enumerate all imported modules?
如何枚举所有导入的模块?
E.g. I would like to get ['os', 'sys']from this code:
例如,我想['os', 'sys']从这段代码中得到:
import os
import sys
采纳答案by Glenn Maynard
import sys
sys.modules.keys()
An approximation of getting all imports for the current module only would be to inspect globals()for modules:
仅获取当前模块的所有导入的近似值是检查globals()模块:
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.
这不会返回本地导入或非模块导入,如from x import y. 请注意,这会返回,val.__name__因此如果您使用了import module as alias,您将获得原始模块名称;如果您想要别名,请改为生成名称。
回答by Mike Axiak
print [key for key in locals().keys()
if isinstance(locals()[key], type(sys)) and not key.startswith('__')]
回答by Marcin
Find the intersection of sys.moduleswith globals:
找到的路口sys.modules有globals:
import sys
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]
回答by fabiand
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 importablemodule names.
这将创建一个包含可导入模块名称的列表。
回答by Lila
If you want to do this from outside the script:
如果您想从脚本外部执行此操作:
Python 2
蟒蛇 2
from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script("myscript.py")
for name, mod in finder.modules.iteritems():
print name
Python 3
蟒蛇 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.
这将打印由 myscript.py 加载的所有模块。
回答by Ohad Cohen
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 sysmodule or modules imported from it.
它不会列出sys从中导入的模块。
回答by mukundha reddy
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.
如果在导入之前和导入之后运行它,就可以看出区别。
回答by Dex
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)
回答by JDonner
Stealing from @Lila (couldn't make a comment because of no formatting), this shows the module's /path/, as well:
从@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()
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!
..适合grepping或你有什么。请注意,时间很长!

