The Python Standard LibraryPython标准库¶
While The Python Language Reference describes the exact syntax and semantics of the Python language, this library reference manual describes the standard library that is distributed with Python. 虽然Python语言参考描述了Python语言的确切语法和语义,但本库参考手册描述了随Python发布的标准库。It also describes some of the optional components that are commonly included in Python distributions.它还描述了Python发行版中通常包含的一些可选组件。
Python’s standard library is very extensive, offering a wide range of facilities as indicated by the long table of contents listed below. Python的标准库非常广泛,提供了各种各样的功能,如下面列出的长目录所示。The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. 该库包含内置模块(用C编写),这些模块提供对系统功能的访问,例如Python程序员无法访问的文件I/O,以及用Python编写的模块,这些模块为日常编程中出现的许多问题提供标准化解决方案。Some of these modules are explicitly designed to encourage and enhance the portability of Python programs by abstracting away platform-specifics into platform-neutral APIs.其中一些模块被明确设计为通过将平台细节抽象为平台无关的API来鼓励和增强Python程序的可移植性。
The Python installers for the Windows platform usually include the entire standard library and often also include many additional components. Windows平台的Python安装程序通常包括整个标准库,并且通常还包括许多附加组件。For Unix-like operating systems Python is normally provided as a collection of packages, so it may be necessary to use the packaging tools provided with the operating system to obtain some or all of the optional components.对于类Unix的操作系统,Python通常作为一组包提供,因此可能需要使用操作系统提供的打包工具来获取部分或全部可选组件。
In addition to the standard library, there is a growing collection of several thousand components (from individual programs and modules to packages and entire application development frameworks), available from the Python Package Index.除了标准库之外,还有越来越多的组件(从单个程序和模块到软件包和整个应用程序开发框架),可从Python软件包索引获得。
Introduction介绍Built-in Functions内置函数Built-in Constants内建常量Built-in Types内置类型Truth Value Testing真值检验Boolean Operations布尔运算 —and
,or
,not
Comparisons比较Numeric Types数值类型 —int
,float
,complex
Iterator Types迭代器类型Sequence Types序列类型 —list
,tuple
,range
Text Sequence Type文本序列类型 —str
Binary Sequence Types二进制序列类型 —bytes
,bytearray
,memoryview
Set Types集类型 —set
,frozenset
Mapping Types映射类型 —dict
Context Manager Types上下文管理器类型Type Annotation Types类型注释类型 — Generic Alias, UnionOther Built-in Types其他内置类型Special Attributes特殊属性
Built-in Exceptions内置异常Text Processing Services文本处理服务string
—Common string operations常用字符串操作re
—Regular expression operations正则表达式操作difflib
—Helpers for computing deltas计算增量的助手textwrap
—Text wrapping and filling文本包装和填充unicodedata
—Unicode DatabaseUnicode数据库stringprep
—Internet String Preparation互联网字符串准备readline
—GNU readline interfaceGNU读线接口rlcompleter
—Completion function for GNU readlineGNU readline的完成函数
Binary Data Services二进制数据服务Data Types数据类型datetime
—Basic date and time types基本日期和时间类型zoneinfo
—IANA time zone supportIANA时区支持calendar
—General calendar-related functions与日历相关的通用功能collections
—Container datatypes容器数据类型collections.abc
—Abstract Base Classes for Containers容器的抽象基类heapq
—Heap queue algorithm堆队列算法bisect
—Array bisection algorithm阵列二分法array
—Efficient arrays of numeric values有效的数值数组weakref
—Weak references弱引用types
—Dynamic type creation and names for built-in types动态类型创建和内置类型的名称copy
—Shallow and deep copy operations浅拷贝和深拷贝操作pprint
—Data pretty printer数据漂亮打印机reprlib
—Alternate备用repr()
implementationrepr()
实现enum
—Support for enumerations支持枚举graphlib
—Functionality to operate with graph-like structures使用类似图形的结构进行操作的功能
Numeric and Mathematical Modules数字和数学模块numbers
—Numeric abstract base classes数字抽象基类math
—Mathematical functions数学函数cmath
—Mathematical functions for complex numbers复数的数学函数decimal
—Decimal fixed point and floating point arithmetic十进制定点和浮点运算fractions
—Rational numbers有理数random
—Generate pseudo-random numbers生成伪随机数statistics
—Mathematical statistics functions数理统计函数
Functional Programming Modules函数式编程模块File and Directory Access文件和目录访问pathlib
—Object-oriented filesystem paths面向对象的文件系统路径os.path
—Common pathname manipulations常见路径名操作fileinput
—Iterate over lines from multiple input streams迭代多个输入流中的行stat
—Interpreting解释stat()
resultsstat()
结果filecmp
—File and Directory Comparisons文件和目录比较tempfile
—Generate temporary files and directories生成临时文件和目录glob
—Unix style pathname pattern expansionUnix风格的路径名模式扩展fnmatch
—Unix filename pattern matchingUnix文件名模式匹配linecache
—Random access to text lines随机访问文本行shutil
—High-level file operations高级文件操作
Data Persistence数据持久层pickle
—Python object serializationPython对象序列化copyreg
—Register注册pickle
support functionspickle
支持函数shelve
—Python object persistencePython对象持久性marshal
—Internal Python object serialization内部Python对象序列化dbm
—Interfaces to Unix “databases”Unix“数据库”的接口sqlite3
—DB-API 2.0 interface for SQLite databasesSQLite数据库的DB-API 2.0接口
Data Compression and Archiving数据压缩和归档File Formats文件格式Cryptographic Services加密服务Generic Operating System Services通用操作系统服务os
—Miscellaneous operating system interfaces其他操作系统接口io
—Core tools for working with streams用于处理流的核心工具time
—Time access and conversions时间访问和转换argparse
—Parser for command-line options, arguments and sub-commands命令行选项、参数和子命令的解析器getopt
—C-style parser for command line options用于命令行选项的C风格解析器logging
—Logging facility for PythonPython的日志记录功能logging.config
—Logging configuration日志记录配置logging.handlers
—Logging handlers日志处理程序getpass
—Portable password input便携式密码输入curses
—Terminal handling for character-cell displays字符单元显示器的终端处理curses.textpad
—Text input widget for curses programscurses程序的文本输入小部件curses.ascii
—Utilities for ASCII charactersASCII字符的实用程序curses.panel
—A panel stack extension for curses用于诅咒的面板堆栈扩展platform
—Access to underlying platform’s identifying data访问底层平台的识别数据errno
—Standard errno system symbols标准无系统符号ctypes
—A foreign function library for PythonPython的外部函数库
Concurrent Execution并行执行threading
—Thread-based parallelism基于线程的并行性multiprocessing
—Process-based parallelism基于进程的并行性multiprocessing.shared_memory
—Provides shared memory for direct access across processes为跨进程直接访问提供共享内存Theconcurrent
packageconcurrent
包concurrent.futures
—Launching parallel tasks启动并行任务subprocess
—Subprocess management子流程管理sched
—Event scheduler事件调度器queue
—A synchronized queue class同步队列类contextvars
—Context Variables上下文变量_thread
—Low-level threading API低级线程API
Networking and Interprocess Communication网络和进程间通信asyncio
—Asynchronous I/O异步输入/输出socket
—Low-level networking interface低层网络接口ssl
—TLS/SSL wrapper for socket objects套接字对象的TLS/SSL包装器select
—Waiting for I/O completion等待I/O完成selectors
—High-level I/O multiplexing高级I/O多路复用signal
—Set handlers for asynchronous events设置异步事件的处理程序mmap
—Memory-mapped file support内存映射文件支持
Internet Data Handling互联网数据处理email
—An email and MIME handling package电子邮件和MIME处理包json
—JSON encoder and decoderJSON编码器和解码器mailcap
—Mailcap file handlingMailcap文件处理mailbox
—Manipulate mailboxes in various formats以各种格式操作邮箱mimetypes
—Map filenames to MIME types将文件名映射到MIME类型base64
—Base16, Base32, Base64, Base85 Data EncodingsBase16、Base32、Base64、Base85数据编码binhex
—Encode and decode binhex4 files对binhex4文件进行编码和解码binascii
—Convert between binary and ASCII在二进制和ASCII之间转换quopri
—Encode and decode MIME quoted-printable data对MIME引用的可打印数据进行编码和解码
Structured Markup Processing Tools结构化标记处理工具html
—HyperText Markup Language support超文本标记语言支持html.parser
—Simple HTML and XHTML parser简单的HTML和XHTML解析器html.entities
—Definitions of HTML general entitiesHTML通用实体的定义XML Processing ModulesXML处理模块xml.etree.ElementTree
—The ElementTree XML APIElementTree XML APIxml.dom
—The Document Object Model API文档对象模型APIxml.dom.minidom
—Minimal DOM implementation最小DOM实现xml.dom.pulldom
—Support for building partial DOM trees支持构建部分DOM树xml.sax
—Support for SAX2 parsers支持SAX2解析器xml.sax.handler
—Base classes for SAX handlersSAX处理程序的基类xml.sax.saxutils
—SAX UtilitiesSAX实用程序xml.sax.xmlreader
—Interface for XML parsersXML解析器接口xml.parsers.expat
—Fast XML parsing using Expat使用Expat快速解析XML
Internet Protocols and Support互联网协议和支持webbrowser
—Convenient web-browser controller方便的web浏览器控制器wsgiref
—WSGI Utilities and Reference ImplementationWSGI实用程序和参考实现urllib
—URL handling modulesURL处理模块urllib.request
—Extensible library for opening URLs用于打开URL的可扩展库urllib.response
—Response classes used by urlliburllib使用的响应类urllib.parse
—Parse URLs into components将URL解析为组件urllib.error
—Exception classes raised by urllib.requesturllib.request
引发的异常类urllib.robotparser
—Parser for robots.txtrobots.txt解析器http
—HTTP modulesHTTP模块http.client
—HTTP protocol clientHTTP协议客户端ftplib
—FTP protocol clientFTP协议客户端poplib
—POP3 protocol clientPOP3协议客户端imaplib
—IMAP4 protocol clientIMAP4协议客户端smtplib
—SMTP protocol clientSMTP协议客户端uuid
—UUID objects according to RFC 4122符合RFC 4122的UUID对象socketserver
—A framework for network servers网络服务器框架http.server
—HTTP serversHTTP服务器http.cookies
—HTTP state managementHTTP状态管理http.cookiejar
—Cookie handling for HTTP clientsHTTP客户端的Cookie处理xmlrpc
—XMLRPC server and client modulesXMLRPC服务器和客户端模块xmlrpc.client
—XML-RPC client accessXML-RPC客户端访问xmlrpc.server
—Basic XML-RPC servers基本XML-RPC服务器ipaddress
—IPv4/IPv6 manipulation libraryIPv4/IPv6操作库
Multimedia Services多媒体服务Internationalization国际化Program Frameworks项目框架Graphical User Interfaces with Tk使用Tk的图形用户界面tkinter
—Python interface to Tcl/TkTcl/Tk的Python接口tkinter.colorchooser
—Color choosing dialog颜色选择对话框tkinter.font
—Tkinter font wrapperTkinter字体包装器Tkinter DialogsTkinter对话框tkinter.messagebox
—Tkinter message promptsTkinter消息提示tkinter.scrolledtext
—Scrolled Text Widget滚动文本小部件tkinter.dnd
—Drag and drop support拖放支持tkinter.ttk
—Tk themed widgetsTk主题小部件tkinter.tix
—Extension widgets for TkTk的扩展小部件- IDLE
Development Tools开发工具typing
—Support for type hints支持类型提示pydoc
—Documentation generator and online help system文档生成器和在线帮助系统Python Development ModePython开发模式Effects of the Python Development ModePython开发模式的影响ResourceWarning Example资源警告示例Bad file descriptor error example错误的文件描述符错误示例doctest
—Test interactive Python examples测试交互式Python示例unittest
—Unit testing framework单元测试框架unittest.mock
—mock object library模拟对象库unittest.mock
—getting started开始- 2to3 -
Automated Python 2 to 3 code translation自动Python 2到3代码转换 test
—Regression tests package for PythonPython回归测试包test.support
—Utilities for the Python test suitePython测试套件的实用程序test.support.socket_helper
—Utilities for socket tests套接字测试实用程序test.support.script_helper
—Utilities for the Python execution testsPython执行测试的实用程序test.support.bytecode_helper
—Support tools for testing correct bytecode generation支持用于测试正确字节码生成的工具test.support.threading_helper
—Utilities for threading tests线程测试实用程序test.support.os_helper
—Utilities for os tests操作系统测试实用程序test.support.import_helper
—Utilities for import tests导入测试的实用程序test.support.warnings_helper
—Utilities for warnings tests警告测试实用程序
Debugging and Profiling调试和分析Audit events table审核事件表bdb
—Debugger framework调试器框架faulthandler
—Dump the Python traceback转储Python回溯pdb
—The Python DebuggerPython调试器The Python ProfilersPython分析器timeit
—Measure execution time of small code snippets测量小代码段的执行时间trace
—Trace or track Python statement execution跟踪或跟踪Python语句执行tracemalloc
—Trace memory allocations跟踪内存分配
Software Packaging and Distribution软件打包和分发Python Runtime ServicesPython运行时服务sys
—System-specific parameters and functions系统特定参数和功能sysconfig
—Provide access to Python’s configuration information提供对Python配置信息的访问builtins
—Built-in objects内置对象__main__
—Top-level code environment顶级代码环境warnings
—Warning control警告控制dataclasses
—Data Classes数据类contextlib
—Utilities forwith
-statement contextswith
语句上下文的实用程序abc
—Abstract Base Classes抽象基类atexit
—Exit handlers出口处理程序traceback
—Print or retrieve a stack traceback打印或检索堆栈回溯__future__
—Future statement definitions未来报表定义gc
—Garbage Collector interface垃圾收集器接口inspect
—Inspect live objects检查带电物体site
—Site-specific configuration hook特定于站点的配置挂钩
Custom Python Interpreters自定义Python解释器Importing Modules导入模块zipimport
—Import modules from Zip archives从压缩文件导入模块pkgutil
—Package extension utility包扩展实用程序modulefinder
—Find modules used by a script查找脚本使用的模块runpy
—Locating and executing Python modules定位和执行Python模块importlib
—The implementation ofimport
import
的实施Using使用importlib.metadata
importlib.metadata
Python Language ServicesPython语言服务ast
—Abstract Syntax Trees抽象语法树symtable
—Access to the compiler’s symbol tables访问编译器的符号表token
—Constants used with Python parse treesPython解析树使用的常量keyword
—Testing for Python keywordsPython关键字测试tokenize
—Tokenizer for Python sourcePython源代码的标记器tabnanny
—Detection of ambiguous indentation模糊缩进检测pyclbr
—Python module browser supportPython模块浏览器支持py_compile
—Compile Python source files编译Python源文件compileall
—Byte-compile Python libraries字节编译Python库dis
—Disassembler for Python bytecodePython字节码反汇编程序pickletools
—Tools for pickle developerspickle开发人员的工具
MS Windows Specific ServicesMS Windows特定服务Unix Specific ServicesUnix特定服务posix
—The most common POSIX system calls最常见的POSIX系统调用pwd
—The password database密码数据库grp
—The group database组数据库termios
—POSIX style tty controlPOSIX风格的tty控件tty
—Terminal control functions终端控制功能pty
—Pseudo-terminal utilities伪终端实用程序fcntl
—Thefcntl
andioctl
system callsfcntl
和ioctl
系统调用resource
—Resource usage information资源使用信息syslog
—Unix syslog library routinesUnix系统日志库例程
Superseded Modules替代模块aifc
—Read and write AIFF and AIFC files读取和写入AIFF和AIFC文件asynchat
—Asynchronous socket command/response handler异步套接字命令/响应处理程序asyncore
—Asynchronous socket handler异步套接字处理程序audioop
—Manipulate raw audio data处理原始音频数据cgi
—Common Gateway Interface support通用网关接口支持cgitb
—Traceback manager for CGI scriptsCGI脚本的回溯管理器chunk
—Read IFF chunked data读取IFF分块数据crypt
—Function to check Unix passwords用于检查Unix密码的函数imghdr
—Determine the type of an image确定图像的类型imp
—Access the import internals访问import
内部构件msilib
—Read and write Microsoft Installer files读取和写入Microsoft安装程序文件nntplib
—NNTP protocol clientNNTP协议客户端nis
—Interface to Sun’s NIS (Yellow Pages)Sun的NIS接口(黄页)optparse
—Parser for command line options命令行选项的解析器ossaudiodev
—Access to OSS-compatible audio devices访问OSS兼容的音频设备pipes
—Interface to shell pipelines外壳管道的接口smtpd
—SMTP ServerSMTP服务器sndhdr
—Determine type of sound file确定声音文件的类型spwd
—The shadow password database影子密码数据库sunau
—Read and write Sun AU files读写Sun-AU文件telnetlib
—Telnet clientTelnet客户端uu
—Encode and decode uuencode files编码和解码uuencode文件xdrlib
—Encode and decode XDR data编码和解码XDR数据
Security Considerations安全注意事项