如何在Python中获取内置模块列表?

60
我希望能够获得Python内置模块名称列表,以便测试函数命名惯例的流行程度(下划线、驼峰式或混合式)。我知道有一个全局模块索引,但我想知道是否有一个更易于使用的字符串列表 :)
更新:
len(dir(__builtins__)) = 145  
len(stdlib_list("2.7")) = 430  
help('modules') = 508 # counting manually the output

7
您可能也想查看PEP8和命名约定。 - Vincent Savard
1
“underline”和“underscore”是同一件事。有关使用_name__name__的约定。内置库中具有大写字符的函数/方法/名称的数量非常少。你的目标是什么? - John Machin
谢谢,文森特。我确实想亲自遍历整个内置模块的函数,以了解当前的命名情况 :) - Drake Guan
9个回答

60
编译的模块名称可在sys.builtin_module_names中找到。要获取所有可导入的模块,请参阅pkgutil.iter_modules
在干净的virtualenv中运行它们,以获得(几乎)仅包含Python本身模块。
请注意,“流行度调查”必然会包括使用旧的、不推荐命名约定的模块,因为它们是在今天制定指南之前编写的,并且不能更改,因为需要向后兼容。它可能对某些事情有用,但不适用于回答最佳实践问题,例如“我应该如何命名我的函数?”。对于这个问题,请参考PEP8,Python风格指南,特别是“命名惯例”部分。

在问题上添加了一条注释,受@VincentSavard的评论启发。谢谢,Vincent。 - Petr Viktorin
1
这些似乎不完整。例如,在Python 2.7中,sys.builtin_module_names和pkgutil.iter_modules()都不包含“collections”或“os”。有人能说出原因吗?是否有解决方案可以返回原问题中全局模块索引中列出的所有内容?编辑:回答我的第一个问题,os和collections是标准库的一部分,而不是内置函数。 - Boon
1
很有趣。在我的Python 2.7(以及3.8),pkgutil.iter_modules()确实包括collectionsos的条目。你得到了哪些类型的模块? - Petr Viktorin
这很尴尬。用户错误。我只是在测试'collections' in list(pkgutil.iter_modules()),它返回了False - Boon

24

抱歉,但这并没有回答问题。问题是关于模块名称,而不是内置模块。 - Regis May

16
现在有一个第三方软件包可以实现这个功能。它会爬取Python官方文档中标准库页面的目录,并生成一个列表。
你可以使用pip安装它。
pip install stdlib_list

并获取一个库列表

In [12]: from stdlib_list import stdlib_list

In [13]: libraries = stdlib_list("3.5")

In [14]: libraries[4:12]
Out[14]: ['abc', 'aifc', 'argparse', 'array', 'ast', 'asynchat', 'asyncio', 'asyncore']

你可以在这里找到源代码

2
这真是太棒了。感谢您提供这些信息。我还将不同方式的软件包数量结果放入了我的原始帖子中。 - Drake Guan

6

>>>dir (__builtins__)

or

>>>help (__builtins__)


正如@Regis May在另一个答案中指出的那样,这个问题涉及到模块,而不是内置函数。 - MinneapolisCoder9

5

来自CPython文档

所有已知的内置模块都列在sys.builtin_module_names中

sys.builtin_module_names中列出的模块名称仅适用于使用的Python解释器:

一个字符串元组,给出编译到此Python解释器中的所有模块的名称

每个内置模块在导入时使用特殊的加载器:BuiltinImporter

In [65]: import itertools, sys, gc

In [66]: itertools.__loader__, sys.__loader__, gc.__loader__
Out[66]: 
(_frozen_importlib.BuiltinImporter,
 _frozen_importlib.BuiltinImporter,
 _frozen_importlib.BuiltinImporter)

在Python 3中,内置模块的数量略有增加。
$ python2.7 -c "import sys; print('Count built-in modules: %d' %len(sys.builtin_module_names)); print(sys.builtin_module_names)"
Count built-in modules: 51
('__builtin__', '__main__', '_ast', '_bisect', '_codecs', '_collections', '_functools', '_heapq', '_io', '_locale', '_md5', '_random', '_sha', '_sha256', '_sha512', '_socket', '_sre', '_struct', '_symtable', '_warnings', '_weakref', 'array', 'binascii', 'cPickle', 'cStringIO', 'cmath', 'datetime', 'errno', 'exceptions', 'fcntl', 'gc', 'grp', 'imp', 'itertools', 'marshal', 'math', 'operator', 'posix', 'pwd', 'select', 'signal', 'spwd', 'strop', 'sys', 'syslog', 'thread', 'time', 'unicodedata', 'xxsubtype', 'zipimport', 'zlib')
$ python3.4 -c "import sys; print('Count built-in modules: %d' %len(sys.builtin_module_names)); print(sys.builtin_module_names)"
Count built-in modules: 54
('_ast', '_bisect', '_codecs', '_collections', '_datetime', '_elementtree', '_functools', '_heapq', '_imp', '_io', '_locale', '_md5', '_operator', '_pickle', '_posixsubprocess', '_random', '_sha1', '_sha256', '_sha512', '_socket', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'array', 'atexit', 'binascii', 'builtins', 'errno', 'faulthandler', 'fcntl', 'gc', 'grp', 'itertools', 'marshal', 'math', 'posix', 'pwd', 'pyexpat', 'select', 'signal', 'spwd', 'sys', 'syslog', 'time', 'unicodedata', 'xxsubtype', 'zipimport', 'zlib')

作为CPython主要是基于C语言实现的,因此很难找到它,例如Python的sys模块(基于this answer)所在位置:
$ locate sysmodule | grep python
/usr/include/python2.7/sysmodule.h
/usr/include/python3.4m/sysmodule.h
/usr/local/include/python3.5m/sysmodule.h

关于获取所有可用模块的信息,可以查看CPython,具体请参见我的回答这里


2

以下代码块是我认为最有效的方法,可以使用它来完成。

import sys
a = sys.builtin_module_names
print(a)

如果您想打印它们,最后一行需要包含在内。 这里,a是一个元组,因此可以访问元组的所有功能。
您可以查看sys.builtin_module_names以获取进一步帮助 https://docs.python.org/3/library/sys.html

3
这仅列出了一些模块,例如sys和time,但不包括其他模块(例如os和random)。 - trajekolus
它不会列出已导入的模块。为此,请尝试使用 modules.keys()。 - Akash Kumar

1

所有类似于dir(builtins)或help(builtins)或sys.builtin_module_names的命令,要么缺少几个核心内置包的名称,要么给出了数千行冗长的输出。

>>> help('modules')

显示所有已安装模块的最佳命令是help('modules')。它会列出Python中所有已安装模块的名称而不会遗漏任何一个。

如果需要仅获取内置模块的名称,请创建一个临时的新环境并在其中执行该命令。这可能会有点慢,但在我的经验中,这是目前为止列出每个单独包的唯一方法。


1
我正在解决一个类似的问题时,了解到 'builtin' 的意思是“此对象没有关联的源文件”。
以下是一种基于手动检查 /lib 和 /Dlls 文件夹的解决方案。 使用“unique”可能是多余的;它在这里是因为我不确定 DLLs 是否严格用于与 Python 一起提供的软件包/它对我尝试解决的另一个问题(查找源软件包的要求)很有用。
from typing import Generator, Iterable
import os, re, sys

def unique(iterable:Iterable, yielded:list=None) -> Generator:
    """
    Iterate over unique elements of an iterable
    examples:
        >>> [*unique('abbcccdddd')]
        ['a', 'b', 'c', 'd']
        >>> [*unique('abcd')]
        ['a', 'b', 'c', 'd']
    """
    yielded = yielded if not isinstance(yielded, type(None)) else []
    for i in iterable:
        if not i in yielded:
            yield i
            yielded.append(i)

def native_modules() -> Generator:
    """
    Every module found:
        under your installation's /lib and /DLLs directories; excuding any under /lib/site-packages/*
        in sys.builtin_module_names
    """
    omitables = 'site-packages __pycache__ .pyo .ico .dll .pdb'.split()
    
    path = lambda folder: os.path.join(sys.exec_prefix, folder)
    tidy = lambda pth: os.path.split(os.path.splitext(pth)[0])[-1] # separate the name from the path and extension, if present
    discriminant = lambda pth: not any(re.match(i, pth) for i in map(re.escape, omitables))
    
    lib = map(tidy, filter(discriminant, os.listdir(path('lib'))))
    dlls = map(tidy, filter(discriminant, os.listdir(path('DLLs'))))

    yielded = []
    yield from yielded
    yield from unique(sys.builtin_module_names, yielded)
    yield from unique(lib, yielded)
    yield from unique(dlls, yielded)

0
在Linux中,您可以使用以下命令获取随新安装的所有内置模块的转储。
sudo apt-get install python3-virtualenv

tmpDir=`mktemp -d`

python3 -m virtualenv $tmpDir
source /tmp/virtualenv/bin/activate
python

help('modules')

示例执行

以下是在Debian 11上使用Python 3.9执行上述命令的示例

user@disp643:~$ sudo apt-get install python3-virtualenv
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
python3-virtualenv is already the newest version (20.4.0+ds-2+deb11u1).
The following packages were automatically installed and are no longer required:
  ethtool libbotan-2-17 libtspi1 linux-image-5.10.0-10-amd64
  linux-image-5.10.0-13-amd64 linux-image-5.10.0-14-amd64
  linux-image-5.10.0-15-amd64 linux-image-5.10.0-16-amd64
  linux-image-5.10.0-17-amd64 net-tools sse3-support
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 4 not upgraded.
user@disp643:~$ 

user@disp643:~$ tmpDir=`mktemp -d`
user@disp643:~$ 

user@disp643:~$ python3 -m virtualenv $tmpDir
created virtual environment CPython3.9.2.final.0-64 in 120ms
  creator CPython3Posix(dest=/tmp/tmp.qQsKZHGZqk, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/user/.local/share/virtualenv)
    added seed packages: pip==20.3.4, pkg_resources==0.0.0, setuptools==44.1.1, wheel==0.34.2
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
user@disp643:~$ source /tmp/virtualenv/bin/activate
(virtualenv) user@disp643:~$ python
Python 3.9.2 (default, Feb 28 2021, 17:03:44) 
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help('modules')

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

__future__          _tracemalloc        graphlib            retrying
_abc                _uuid               grp                 rlcompleter
_aix_support        _virtualenv         gzip                runpy
_ast                _warnings           hashlib             sched
_asyncio            _weakref            heapq               secrets
_bisect             _weakrefset         hmac                select
_blake2             _xxsubinterpreters  html                selectors
_bootlocale         _xxtestfuzz         html5lib            setuptools
_bootsubprocess     _zoneinfo           http                shelve
_bz2                abc                 idna                shlex
_codecs             aifc                imaplib             shutil
_codecs_cn          antigravity         imghdr              signal
_codecs_hk          appdirs             imp                 site
_codecs_iso2022     argparse            importlib           sitecustomize
_codecs_jp          array               inspect             smtpd
_codecs_kr          ast                 io                  smtplib
_codecs_tw          asynchat            ipaddr              sndhdr
_collections        asyncio             ipaddress           socket
_collections_abc    asyncore            itertools           socketserver
_compat_pickle      atexit              json                spwd
_compression        audioop             keyword             sqlite3
_contextvars        base64              lib2to3             sre_compile
_crypt              bdb                 linecache           sre_constants
_csv                binascii            locale              sre_parse
_ctypes             binhex              logging             ssl
_ctypes_test        bisect              lzma                stat
_curses             builtins            mailbox             statistics
_curses_panel       bz2                 mailcap             string
_datetime           cProfile            marshal             stringprep
_dbm                calendar            math                struct
_decimal            certifi             mimetypes           subprocess
_elementtree        cgi                 mmap                sunau
_functools          cgitb               modulefinder        symbol
_hashlib            chunk               msgpack             symtable
_heapq              cmath               multiprocessing     sys
_imp                cmd                 netrc               sysconfig
_io                 code                nis                 syslog
_json               codecs              nntplib             tabnanny
_locale             codeop              ntpath              tarfile
_lsprof             collections         nturl2path          telnetlib
_lzma               colorama            numbers             tempfile
_markupbase         colorsys            opcode              termios
_md5                compileall          operator            test
_multibytecodec     concurrent          optparse            textwrap
_multiprocessing    configparser        os                  this
_opcode             contextlib          ossaudiodev         threading
_operator           contextlib2         packaging           time
_osx_support        contextvars         parser              timeit
_peg_parser         copy                pathlib             tkinter
_pickle             copyreg             pdb                 token
_posixshmem         crypt               pep517              tokenize
_posixsubprocess    csv                 pickle              toml
_py_abc             ctypes              pickletools         trace
_pydecimal          curses              pip                 traceback
_pyio               dataclasses         pipes               tracemalloc
_queue              datetime            pkg_resources       tty
_random             dbm                 pkgutil             turtle
_sha1               decimal             platform            types
_sha256             difflib             plistlib            typing
_sha3               dis                 poplib              unicodedata
_sha512             distlib             posix               unittest
_signal             distutils           posixpath           urllib
_sitebuiltins       doctest             pprint              urllib3
_socket             easy_install        profile             uu
_sqlite3            email               progress            uuid
_sre                encodings           pstats              venv
_ssl                enum                pty                 warnings
_stat               errno               pwd                 wave
_statistics         faulthandler        py_compile          weakref
_string             fcntl               pyclbr              webbrowser
_strptime           filecmp             pydoc               wheel
_struct             fileinput           pydoc_data          wsgiref
_symtable           fnmatch             pyexpat             xdrlib
_sysconfigdata__linux_x86_64-linux-gnu formatter           pyparsing           xml
_sysconfigdata__x86_64-linux-gnu fractions           queue               xmlrpc
_testbuffer         ftplib              quopri              xxlimited
_testcapi           functools           random              xxsubtype
_testimportmultiple gc                  re                  zipapp
_testinternalcapi   genericpath         readline            zipfile
_testmultiphase     getopt              reprlib             zipimport
_thread             getpass             requests            zlib
_threading_local    gettext             resolvelib          zoneinfo
_tkinter            glob                resource            

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

>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接