问题描述
有没有一种不使用__all__
的直接列出包中所有模块名称的方法?
例如,给定这个包:
/testpkg/testpkg/__init__.py/testpkg/modulea.py/testpkg/moduleb.py
我想知道是否有标准或内置的方式来做这样的事情:
>>>包内容(testpkg")['modulea', 'moduleb']手动方法是遍历模块搜索路径以找到包的目录.然后可以列出该目录中的所有文件,过滤掉唯一命名的 py/pyc/pyo 文件,去除扩展名,然后返回该列表.但是对于模块导入机制已经在内部做的事情来说,这似乎是相当多的工作.该功能是否在任何地方公开?
也许这会满足您的需求?
导入导入导入操作系统MODULE_EXTENSIONS = ('.py', '.pyc', '.pyo')def package_contents(package_name):文件,路径名,描述 = imp.find_module(package_name)如果文件:raise ImportError('不是包:%r', package_name)# 使用集合,因为有些可能既是源代码又是编译好的.返回集([os.path.splitext(模块)[0]对于 os.listdir(pathname) 中的模块如果 module.endswith(MODULE_EXTENSIONS)])
Is there a straightforward way to list the names of all modules in a package, without using __all__
?
For example, given this package:
/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
I'm wondering if there is a standard or built-in way to do something like this:
>>> package_contents("testpkg")
['modulea', 'moduleb']
The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?
Maybe this will do what you're looking for?
import imp
import os
MODULE_EXTENSIONS = ('.py', '.pyc', '.pyo')
def package_contents(package_name):
file, pathname, description = imp.find_module(package_name)
if file:
raise ImportError('Not a package: %r', package_name)
# Use a set because some may be both source and compiled.
return set([os.path.splitext(module)[0]
for module in os.listdir(pathname)
if module.endswith(MODULE_EXTENSIONS)])
这篇关于有没有标准的方法来列出包中 Python 模块的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!