如何列出调用/b
时导入的内容。我已经尝试过sys.modules.keys()但是这个提供了更多的低级数据类型。
答案 0 :(得分:4)
您应该在没有foo
的情况下导入*
,这样您就可以dir
使用foo
获取所有名称:
import foo
print dir(foo)
答案 1 :(得分:2)
作为一般Python规则,运行from foo import *
被认为是坏样式(非pythonic),因为它污染了命名空间。
我对你的问题进行了一些思考,这就是我想出来的。使用iPython方便的%paste
魔术功能将以下内容复制/粘贴到iPython中,或将其保存到脚本中并直接运行:
import pkgutil
def list_all_modules(top_level_package):
modnames = []
package = top_level_package
prefix = package.__name__ + "."
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
modnames.append(modname)
if ispkg:
module = __import__(modname, fromlist="dummy")
recurse_modnames = list_all_modules(module)
modnames += recurse_modnames
return modnames
现在您可以导入模块/库foo
,将其传递给此函数,并返回包str
下所有可用模块/子模块的列表(foo
个对象) 。像这样:
modnames = list_all_modules(foo)
print modnames
作为测试,我会在html5lib
库提供here。
In [2]: from pprint import pprint
In [3]: import html5lib
In [4]: modnames = list_all_modules(html5lib)
In [5]: pprint(modnames)
['html5lib.constants',
'html5lib.filters',
'html5lib.filters._base',
'html5lib.filters.alphabeticalattributes',
'html5lib.filters.inject_meta_charset',
'html5lib.filters.lint',
'html5lib.filters.optionaltags',
'html5lib.filters.sanitizer',
'html5lib.filters.whitespace',
'html5lib.html5parser',
'html5lib.ihatexml',
'html5lib.inputstream',
'html5lib.sanitizer',
'html5lib.serializer',
'html5lib.serializer.htmlserializer',
'html5lib.tokenizer',
'html5lib.treeadapters',
'html5lib.treeadapters.sax',
'html5lib.treebuilders',
'html5lib.treebuilders._base',
'html5lib.treebuilders.dom',
'html5lib.treebuilders.etree',
'html5lib.treebuilders.etree_lxml',
'html5lib.treewalkers',
'html5lib.treewalkers._base',
'html5lib.treewalkers.dom',
'html5lib.treewalkers.etree',
'html5lib.treewalkers.genshistream',
'html5lib.treewalkers.lxmletree',
'html5lib.treewalkers.pulldom',
'html5lib.trie',
'html5lib.trie._base',
'html5lib.trie.datrie',
'html5lib.trie.py',
'html5lib.utils']
这绝对感觉像是一种非pythonic方式,但如果有人有更好的方法,请告诉我。 :)