你可以使用
pkgutil。这会列出 /usr/lib/python2.6/site-packages 下的所有模块:(与
sys.modules
不同,这不需要您先导入模块就能列出它们)。
import pkgutil
print [name for module_loader,name,ispkg in
pkgutil.walk_packages(['/usr/lib/python2.6/site-packages'])]
编辑::
文档没有列出
walk_packages
。但是,
pkgutil
在
pkgutil.__all__
中包含了
walk_packages
。这意味着它是 pkgutil 的公共接口的一部分。您可以在 /usr/lib/python2.6/pkgutil.py 中找到关于
walk_packages
的以下文档,或者输入
help(pkgutil.walk_packages)
:
Definition: pkgutil.walk_packages(path=None, prefix='', onerror=None)
Docstring:
Yields (module_loader, name, ispkg) for all modules recursively
on path, or, if path is None, all accessible modules.
'path' should be either None or a list of paths to look for
modules in.
'prefix' is a string to output on the front of every module name
on output.
Note that this function must import all *packages* (NOT all
modules!) on the given path, in order to access the __path__
attribute to find submodules.
'onerror' is a function which gets called with one argument (the
name of the package which was being imported) if any exception
occurs while trying to import a package. If no onerror function is
supplied, ImportErrors are caught and ignored, while all other
exceptions are propagated, terminating the search.
Examples:
walk_packages()
walk_packages(ctypes.__path__, ctypes.__name__+'.')
from distutils.sysconfig import get_python_lib; print(get_python_lib())
。 - nealmcb