如何访问 Python 的帮助(“模块”)显示的模块列表?

发布于 2024-12-26 10:45:27 字数 638 浏览 0 评论 0原文

如何访问 Python 的 help('modules') 显示的模块列表?它显示以下内容:

>>> help('modules')

Please wait a moment while I gather a list of all available modules...

...[list of modules]...
MySQLdb             codeop              mailman_sf          spwd
OpenSSL             collections         markupbase          sqlite3
Queue               colorsys            marshal             sre
...[list of modules]...

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

>>>

我可以查看输出中的列表,但希望从 Python 程序中将其作为列表进行访问。我该怎么做?

How can I access the list of modules that Python's help('modules') displays? It shows the following:

>>> help('modules')

Please wait a moment while I gather a list of all available modules...

...[list of modules]...
MySQLdb             codeop              mailman_sf          spwd
OpenSSL             collections         markupbase          sqlite3
Queue               colorsys            marshal             sre
...[list of modules]...

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

>>>

I can view the list in the output but would like to access this as a list from within a Python program. How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

眼趣 2025-01-02 10:45:28

方法不止一种。你可以尝试:

import sys

mod_dict = sys.modules

for k,v in mod_dict.iteritems():
    print k,v

There are more then one way. You could try:

import sys

mod_dict = sys.modules

for k,v in mod_dict.iteritems():
    print k,v
佼人 2025-01-02 10:45:28

模块列表最终来自 sys.builtin_module_namespkgutil.walk_packages 的输出:

import sys
from pkgutil import walk_packages

modules = set()

def callback(name, modules=modules):
    if name.endswith('.__init__'):
        name = name[:-9] + ' (package)'
    if name.find('.') < 0:
        modules.add(name)

for name in sys.builtin_module_names:
    if name != '__main__':
        callback(name)

for item in walk_packages(onerror=callback):
    callback(item[1])

for name in sorted(modules, key=lambda n: n.lower()):
    print name

它应该请注意,创建列表的结果是所有模块都将被导入(您可以通过在调用 help('modules 之前和之后检查 sys.modules 的长度来轻松验证这一点'))。

另一件需要注意的事情是 walk_packages 的输出取决于 sys.path 的当前状态 - 因此结果可能并不总是与 help 的输出匹配代码>.

The list of modules comes ultimately from a combination of sys.builtin_module_names and the output of pkgutil.walk_packages:

import sys
from pkgutil import walk_packages

modules = set()

def callback(name, modules=modules):
    if name.endswith('.__init__'):
        name = name[:-9] + ' (package)'
    if name.find('.') < 0:
        modules.add(name)

for name in sys.builtin_module_names:
    if name != '__main__':
        callback(name)

for item in walk_packages(onerror=callback):
    callback(item[1])

for name in sorted(modules, key=lambda n: n.lower()):
    print name

It should be noted that creating the list has the consequnce that all the modules will be imported (you can easily verify this for yourself by checking the length of sys.modules before and after calling help('modules')).

Another thing to note is that the output of walk_packages depends on the current state of sys.path - so the results may not always match the output of help.

一花一树开 2025-01-02 10:45:28

这些只会列出标准库中未包含的模块,
但可能有用,

subprocess.call(
pip 冻结)

subprocess.call(
蛋黄 -l)

Those will only list modules not included in the standard library,
but may be useful,

subprocess.call(
pip freeze)

subprocess.call(
yolk -l)

只怪假的太真实 2025-01-02 10:45:27

您可以自己模仿 help 所做的所有操作。内置 help 使用 pydoc,它使用 ModuleScanner 类来获取有关所有可用库的信息 - 请参阅 pydoc.py

这是链接中代码的稍微修改版本:

>>> modules = []
>>> def callback(path, modname, desc, modules=modules):
    if modname and modname[-9:] == '.__init__':
        modname = modname[:-9] + ' (package)'
    if modname.find('.') < 0:
        modules.append(modname)

>>> def onerror(modname):
    callback(None, modname, None)

>>> from pydoc import ModuleScanner 
>>> ModuleScanner().run(callback, onerror=onerror)
>>> len(modules)
379
>>> modules[:10]
['__builtin__', '_ast', '_bisect', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw']
>>> len(modules)
379

You can mimic all the help does by yourself. Built-in help uses pydoc, that uses ModuleScanner class to get information about all available libs - see line 1873 in pydoc.py.

Here is a bit modified version of code from the link:

>>> modules = []
>>> def callback(path, modname, desc, modules=modules):
    if modname and modname[-9:] == '.__init__':
        modname = modname[:-9] + ' (package)'
    if modname.find('.') < 0:
        modules.append(modname)

>>> def onerror(modname):
    callback(None, modname, None)

>>> from pydoc import ModuleScanner 
>>> ModuleScanner().run(callback, onerror=onerror)
>>> len(modules)
379
>>> modules[:10]
['__builtin__', '_ast', '_bisect', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw']
>>> len(modules)
379
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文