来自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,具体请参见我的回答这里。
_name
和__name__
的约定。内置库中具有大写字符的函数/方法/名称的数量非常少。你的目标是什么? - John Machin